ggplot分组条形图

编程入门 行业动态 更新时间:2024-10-26 15:17:00
本文介绍了ggplot分组条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下数据集:

年份生成的拒绝 1 2012 133118208 7256986 2 2013 289487598 49652610 3 2014 192232775 31765480 4 2015 40434968 2513930

我在尝试生成一个分组的条形图,该分组的条形图将在x轴上具有年并且在y轴上具有数字刻度以显示每年被拒绝的生成的Vs。

我很困惑我应该怎样设定我的y轴?我还没有尝试过使用 spread()函数,因为我希望可能有一个更简单的方法

解决方案

首先,您必须按正确的格式安排数据以进行绘图:

library(重新塑形2) df1 < - melt(df,id =Year)

你可以使用 tidyr 包:

library(tidyr) df1 < - gather(df,variable,value,-Year)

这可能更容易如果你不熟悉 melt()

基本上它说:收集所有 df 中除年之外的变量,调用新的键列变量和新值列值

library(ggplot2) ggplot(df1,aes(Year,value))+ geom_bar(aes(fill = variable),position =dodge,stat =identity)

如果您更喜欢使用逗号分隔数千个数字:

library(ggplot2) library(scales) ggplot(df1,aes(Year,value))+ geom_bar(aes(fill = variable),position =dodge,stat =identity)+ scale_y_continuous(name = 值,标签=逗号)

I have the following dataset:

Year Generated Rejected 1 2012 133118208 7256986 2 2013 289487598 49652610 3 2014 192232775 31765480 4 2015 40434968 2513930

I am trying to generate a grouped bar chart that will have Year on the x axis and a numerical scale on the y axis to show the generated Vs rejected year-wise.

I am confused what I should set my y axis to? I have not tried using the spread() function yet, as I am hoping there might be an easier way

解决方案

First you have to arrange the data in the proper format for plotting:

library(reshape2) df1 <- melt(df, id = "Year")

Or you could use the tidyr package:

library(tidyr) df1 <- gather(df, variable, value, -Year)

Which may be easier to understand if you are not familiar with melt()

Basically, it says: "Gather all the variables in df except Year, calling the new key column variable and the new value column value"

library(ggplot2) ggplot(df1, aes(Year, value)) + geom_bar(aes(fill = variable), position = "dodge", stat = "identity")

If you prefer to format numbers with commas separating thousands:

library(ggplot2) library(scales) ggplot(df1, aes(Year, value)) + geom_bar(aes(fill = variable), position = "dodge", stat = "identity") + scale_y_continuous(name = "Values", labels = comma)

更多推荐

ggplot分组条形图

本文发布于:2023-07-18 00:48:32,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条形图   ggplot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!