【发布时间】:2020-07-08 08:41:36
【问题描述】:
我想创建一个在 x 轴上显示 36 个刻度的图形。
我有 df 在这个例子中我需要 12 个刻度来显示文本。
period agg1 agg2
201601 1 2
201602 2 2
201603 3 2
. . .
. . .
. . .
201612 4 1
period 是数字,格式为 YYYYMM,所以我将其更改为日期
for (row in 1:nrow(df)){
df[row,'period'] <- df[row,'period'] %>%
mutate(period = as.Date(as.character(period*100+25),"%Y%m%d"))
}
融化数据
long_df <- melt(df, id = "period")
我使用以下方法绘制数据:
df_plot <- ggplot(data = long_df,
aes(x = period, y = value, colour = variable)) +
geom_line()
# adding titles & labels
df_plot + labs(title = "Aggregates", colour = "Method") +
xlab("Period") +
ylab("Agg, £million") +
scale_x_discrete(breaks = c("201601", "201602", "201603", "201604", "201605", "201606", "201607", "201608", "201609", "201610", "201611", "201612"))
这会创建一个图表,其中刻度线位于正确的位置,但文本不会显示在刻度线处。
我尝试添加 labels = c() 参数,但它没有显示任何内容
df_plot + labs(title = "Aggregates", colour = "Method") +
xlab("Period") +
ylab("Agg") +
scale_x_discrete(breaks = c("201601", "201602", "201603", "201604", "201605", "201606", "201607", "201608", "201609", "201610", "201611", "201612"),
labels = c("201601", "201602", "201603", "201604", "201605", "201606", "201607", "201608", "201609", "201610", "201611", "201612"))
我发现了这个:ggplot x-axis labels with all x-axis values 但根据解决方案,我的labels 参数应该有效吗?
【问题讨论】:
-
如果你的 x 轴是一个日期,你想使用类似
scale_x_date(date_breaks = "1 day", date_labels = "%Y%m")的东西。请参阅此问题/答案:stackoverflow.com/questions/60764841/… -
@Laura:您不必使用
for循环来更改日期。只需直接在df上使用mutate。它适用于所有行
标签: r ggplot2 label axis-labels