英文:
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 <- gapminder::gapminder |>
rename(deaths = lifeExp) |>
mutate(burden = if_else(continent %in% c("Africa", "America"), "high burden countries", "low_burden_countries"))
# Order
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"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论