ggplot2:条形图错误 - X 轴显示不正确
ggplot2 : Error in barplot - X axis displayed improperly
我有一个数据显示 2013 年和 2014 年的总销售额。
yr_sales
Year sum_amount
1 2013 277125.0
2 2014 331721.8
我想绘制一个条形图,X 轴为年份,Y 轴为销售额。
ggplot(yr_sales, aes(x=Year, y=sum_amount)) +
geom_bar(stat="identity", fill="lightblue", colour="black")
但我得到的只是一个混乱的 X 轴:
我的预期输出是(正如我在 MS Excel 中得到的)
您的年份被视为数值变量。您想要显示数据的方式要求它是一个因素(即,它具有离散值并且不能有年份 2013.5
)。
为您的 x 轴的美学映射设置 as.factor(Year)
:
ggplot(yr_sales, aes(x=as.factor(Year), y=sum_amount)) +
geom_bar(stat="identity", fill="lightblue", colour="black")
您也可以更改数据本身,但是当您希望将年份作为实际数值变量时,这可能会导致问题:
yr_sales$Year = as.factor(yr_sales$Year)
如果你这样做了,你就不需要在美学映射中使用as.factor
。
使用@slhck 给出的答案,我做了以下事情:
ggplot(yr_sales, aes(x=as.factor(Year), y=sum_amount,width=0.4)) +
geom_bar(stat="identity", fill="blue", colour="black")
而且我的输出很完美..
我有一个数据显示 2013 年和 2014 年的总销售额。
yr_sales
Year sum_amount
1 2013 277125.0
2 2014 331721.8
我想绘制一个条形图,X 轴为年份,Y 轴为销售额。
ggplot(yr_sales, aes(x=Year, y=sum_amount)) +
geom_bar(stat="identity", fill="lightblue", colour="black")
但我得到的只是一个混乱的 X 轴:
我的预期输出是(正如我在 MS Excel 中得到的)
您的年份被视为数值变量。您想要显示数据的方式要求它是一个因素(即,它具有离散值并且不能有年份 2013.5
)。
为您的 x 轴的美学映射设置 as.factor(Year)
:
ggplot(yr_sales, aes(x=as.factor(Year), y=sum_amount)) +
geom_bar(stat="identity", fill="lightblue", colour="black")
您也可以更改数据本身,但是当您希望将年份作为实际数值变量时,这可能会导致问题:
yr_sales$Year = as.factor(yr_sales$Year)
如果你这样做了,你就不需要在美学映射中使用as.factor
。
使用@slhck 给出的答案,我做了以下事情:
ggplot(yr_sales, aes(x=as.factor(Year), y=sum_amount,width=0.4)) +
geom_bar(stat="identity", fill="blue", colour="black")
而且我的输出很完美..