在R中创建分组条形图时间序列?

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

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 &quot;stacked&quot; 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=&quot;blue&quot;), stat=&quot;identity&quot;, position=&quot;dodge&quot;)+
      geom_bar(mapping=aes(x=year, y=dont_know, fill=&quot;red&quot;), stat=&quot;identity&quot;, position=&quot;dodge&quot;)


  [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 %&gt;% select(everything()) %&gt;%
	pivot_longer(.,
		cols=c(great_deal,only_some,hardly_any,dont_know),
		names_to=&quot;Var&quot;,
		values_to=&quot;Val&quot;) %&gt;%
	ggplot(aes(y=Val,x=year,fill=Var))+
	geom_bar(stat=&quot;identity&quot;, position=&quot;dodge&quot;)

huangapple
  • 本文由 发表于 2023年6月22日 01:01:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525600.html
匿名

发表评论

匿名网友

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

确定