英文:
Grouped bar chart time series in R?
问题
我想制作一个分组条形图,其中给定年份的四个值(分别对应四列,如great_deal、only_some等)在时间序列中彼此分组。然而,当我运行下面的代码时,它显示的是一个"堆叠"而不是分组的条形图。有人知道我如何编写正确的代码来制作这样一个使用ggplot2的分组条形图吗?
ggplot(confinan) +
geom_bar(mapping=aes(x=year, y=great_deal, fill="blue"), stat="identity", position="dodge") +
geom_bar(mapping=aes(x=year, y=dont_know, fill="red"), stat="identity", position="dodge")
<details>
<summary>英文:</summary>
I have a **csv file** in the format shown below.
[![enter image description here][1]][1]
I would like to plot a **grouped bar chart**, where the four values (one for each of the four columns like great_deal, only_some, etc) for a **given year are grouped** next to each other in a time series. However, when I run the code below, it displays a "stacked" and not grouped bar chart. Does anyone know how I might write the correct code for such a grouped bar chart using **ggplot2**?
ggplot(confinan)+
geom_bar(mapping=aes(x=year, y=great_deal, fill="blue"), stat="identity", position="dodge")+
geom_bar(mapping=aes(x=year, y=dont_know, fill="red"), stat="identity", position="dodge")
[1]: https://i.stack.imgur.com/zv5fM.png
</details>
# 答案1
**得分**: 1
我可以得到您所需的图表,方法是在 `ggplot` 之前执行 `pivot_longer()`,代码如下:
```R
confinan %>%
select(everything()) %>%
pivot_longer(.,
cols=c(great_deal,only_some,hardly_any,dont_know),
names_to="Var",
values_to="Val") %>%
ggplot(aes(y=Val,x=year,fill=Var))+
geom_bar(stat="identity", position="dodge")
英文:
I was able to get your desired chart by doing a pivot_longer()
thrown in before the ggplot
like so
confinan %>% select(everything()) %>%
pivot_longer(.,
cols=c(great_deal,only_some,hardly_any,dont_know),
names_to="Var",
values_to="Val") %>%
ggplot(aes(y=Val,x=year,fill=Var))+
geom_bar(stat="identity", position="dodge")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论