我有一个类似于以下内容的df:
df <-
structure(list(Month = c(201701, 201702, 201703, 201704, 201705, 201706,
201707, 201708, 201709, 201710, 201711, 201712,
201801, 201802, 201803, 201804, 201805, 201806,
201807, 201808, 201809, 201810, 201811, 201812),
Category = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L,
4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L,
1L, 2L, 3L, 4L, 5L, 6L),
.Label = c("A", "B", "C", "D", "E", "F"),
class = "factor"),
Percentage = c(0.46, 0.47, 0.14, 0.42, 0.32, 0.26, 0.37,
0.07, 0.33, 0.35, 0.23, 0.36, 0.47, 0.13,
0.23, 0.47, 0.49, 0.06, 0.24, 0.28, 0.45,
0.07, 0.49, 0.47)),
class = "data.frame", row.names = c(NA, -24L))
月:采用以下格式(“ 201701”,“ 201702”,(...),“ 201805”)
类别 :(“ A”,“ B”,“ C”等)
百分比 :(“ 0.01”,“ 0.03”,“ 0.06”等)
当我将其绘制为:
ggplot(df, aes(x = Month, y = Percentage, color = Category)) +
geom_line() + scale_x_continuous()
它仅返回3个x轴标签,并且它们已从原始数据集中更改。
有人知道如何以原始格式显示所有标签吗?
谢谢!
答案 0 :(得分:1)
这应该可以在X轴上显示所有值,如果不起作用,请使用dput(df)
scale_x_continuous("Month",as.character(Month), breaks = Month)
答案 1 :(得分:1)
您可以将“月份”列转换为正确的日期列,然后进行绘制。然后,您将在日期刻度上得到一个x轴,并按期望的顺序进行排序。
df$Month <- as.Date(paste0(df$Month, "01"), format = "%Y%m%d")
ggplot(df, aes(x = Month, y = Percentage, color = Category)) +
geom_line()
您甚至可以使用scale_x_date
来修改中断和x轴外观:
ggplot(df, aes(x = Month, y = Percentage, color = Category)) +
geom_line() +
scale_x_date(date_breaks = "3 months", date_labels = "%Y%m")
数据
df <-
structure(list(Month = c(201701, 201702, 201703, 201704, 201705, 201706,
201707, 201708, 201709, 201710, 201711, 201712,
201801, 201802, 201803, 201804, 201805, 201806,
201807, 201808, 201809, 201810, 201811, 201812),
Category = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L,
4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L,
1L, 2L, 3L, 4L, 5L, 6L),
.Label = c("A", "B", "C", "D", "E", "F"),
class = "factor"),
Percentage = c(0.46, 0.47, 0.14, 0.42, 0.32, 0.26, 0.37,
0.07, 0.33, 0.35, 0.23, 0.36, 0.47, 0.13,
0.23, 0.47, 0.49, 0.06, 0.24, 0.28, 0.45,
0.07, 0.49, 0.47)),
class = "data.frame", row.names = c(NA, -24L))