ggplot 分组条形图
ggplot grouped bar chart
我有以下数据集:
Year Generated Rejected
1 2012 133118208 7256986
2 2013 289487598 49652610
3 2014 192232775 31765480
4 2015 40434968 2513930
我正在尝试生成一个分组条形图,其中 x 轴为 Year
,y 轴为数字刻度,以显示生成的 Vs 逐年拒绝。
我不知道应该将 y 轴设置为什么?我还没有尝试使用 spread()
函数,因为我希望有更简单的方法
首先,您必须以正确的格式排列数据以进行绘图:
library(reshape2)
df1 <- melt(df, id = "Year")
或者您可以使用 tidyr
包:
library(tidyr)
df1 <- gather(df, variable, value, -Year)
不熟悉的人可能更容易理解melt()
基本上,它表示:"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")
如果您更喜欢用逗号分隔千位来格式化数字:
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)
我有以下数据集:
Year Generated Rejected
1 2012 133118208 7256986
2 2013 289487598 49652610
3 2014 192232775 31765480
4 2015 40434968 2513930
我正在尝试生成一个分组条形图,其中 x 轴为 Year
,y 轴为数字刻度,以显示生成的 Vs 逐年拒绝。
我不知道应该将 y 轴设置为什么?我还没有尝试使用 spread()
函数,因为我希望有更简单的方法
首先,您必须以正确的格式排列数据以进行绘图:
library(reshape2)
df1 <- melt(df, id = "Year")
或者您可以使用 tidyr
包:
library(tidyr)
df1 <- gather(df, variable, value, -Year)
不熟悉的人可能更容易理解melt()
基本上,它表示:"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")
如果您更喜欢用逗号分隔千位来格式化数字:
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)