我有以下数据框:
months = c(1,2,3,4,5,6,7,8,9,10,11,12)
totals = c(437318,406597,454125,432062,443323,414061,418627,428530,400509,427900,378849,344718)
test_df = data.frame(months, totals)
我使用以下代码创建了一个图:
test_df %>%
ggplot(aes(x=months, y=totals)) +
geom_bar(stat='identity', fill='red3') +
scale_y_continuous(breaks=scales::breaks_extended(n=10)) +
ggtitle('Amount by Month') +
ylab('Amount') +
xlab('Month')
ggplot假定x轴包含一个连续变量。我认为这是因为test_df $ months是整数类型。我尝试通过首先创建月份名称数组来编辑我的绘图代码:
个月= c('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
,然后将其添加到绘图代码中:
scale_x_discrete(“月”,月)
但这没用。
如何使x轴显示为月份或月份名称的整数值?
答案 0 :(得分:1)
您可以使用内置向量month.abb
:
library(dplyr)
library(ggplot2)
test_df %>%
mutate(months = factor(month.abb[months], levels = month.abb)) %>%
ggplot(aes(x=months, y=totals)) +
geom_bar(stat='identity', fill='red3') +
scale_y_continuous(breaks=scales::breaks_extended(n=10)) +
ggtitle('Amount by Month') +
ylab('Amount') +
xlab('Month')