如何重新排列堆叠面积图?

huangapple go评论74阅读模式
英文:

How Do I Rearrange a Stacked Area Plot?

问题

以下是您要翻译的内容:

我对R和使用ggplot2创建堆叠面积图还相当新。我已经做到了这一步:

如何重新排列堆叠面积图?

使用以下代码:

ggplot(df, aes(year, deaths, group=country, fill=burden)) +
geom_area() +
geom_area() +
scale_fill_manual(values=c("#999999", "dark red"))

我遇到的问题是,我想让所有红色国家分组在一起,灰色国家也是如此,就像这样:

如何重新排列堆叠面积图?

以下代码生成了正确的图表,但没有图例:

ggplot(modeldf1, mapping = aes(year, deaths, group=country)) + 
geom_area(fill="light grey") +
geom_area(fill="dark red",
        data=modeldf1 %>% filter(country %in% high_burden_countries))
英文:

I am quite new to R and creating a stacked area plot with ggplot2. I have managed to get this far:

如何重新排列堆叠面积图?

using the following code:

ggplot(df,aes(year,deaths,group=country, fill=burden)) +
 
geom_area() +


geom_area() +

scale_fill_manual(values=c("#999999", "dark red")

The issue I am having is that I would like all the red countries to be grouped together, and the same for grey countries, like this:

如何重新排列堆叠面积图?

The following returns the correct plot, but without a legend:

ggplot(modeldf1, mapping = aes(year,deaths,group=country)) + 
geom_area(fill="light grey") +
geom_area(fill="dark red",
        data=modeldf1 %>% filter(country %in% high_burden_countries)) 

答案1

得分: 1

请参考以下翻译:

一种选项是按照burden来排列您的数据,然后将country转换为一个factor,其级别的顺序根据数据的顺序设置,可以通过forecast::fct_inorder实现:

使用基于gapminder::gapminder数据集的最小可重现示例:

library(ggplot2)
library(dplyr)
library(forcats)

df <- gapminder::gapminder %>%
  rename(deaths = lifeExp) %>%
  mutate(burden = if_else(continent %in% c("Africa", "America"), "high burden countries", "low burden countries"))

# 排序
df <- df %>%
  arrange(burden) %>%
  mutate(country = forcats::fct_inorder(country))

ggplot(df, aes(year, deaths, group = country, fill = burden)) +
  geom_area() +
  scale_fill_manual(values = c("#999999", "dark red"))

如何重新排列堆叠面积图?

英文:

One option would be to arrange your data by burden, then convert country to a factor which the order of the levels set according to the order of the data, which could be achieved via forecast::fct_inorder:

Using a minimal repdroducible example based on the gapminder::gapminder dataset:

library(ggplot2)
library(dplyr)
library(forcats)

df &lt;- gapminder::gapminder |&gt; 
  rename(deaths = lifeExp) |&gt; 
  mutate(burden = if_else(continent %in% c(&quot;Africa&quot;, &quot;America&quot;), &quot;high burden countries&quot;, &quot;low_burden_countries&quot;))

# Order
df &lt;- df |&gt; 
  arrange(burden) |&gt; 
  mutate(country = forcats::fct_inorder(country))

ggplot(df, aes(year, deaths, group = country, fill = burden)) +
  geom_area() +
  scale_fill_manual(values = c(&quot;#999999&quot;, &quot;dark red&quot;))

如何重新排列堆叠面积图?

huangapple
  • 本文由 发表于 2023年4月11日 12:46:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定