ggplot2 不显示 Y 轴的值

ggplot2 not displaying values of the Y axis

我尝试获取 Y 轴的值显示,但似乎我无法弄清楚问题所在,这是我的代码和除数据外的绘图结果:

library(ggplot2)

traffic.data <- structure(list(years = 2008:2017, units = structure(c(1L, 2L, 4L, 5L, 3L, 6L, 7L, 8L, 9L, 10L), .Label = c("12,866,461", "13,350,011", "15,106,666", "15,361,841", "15,669,918", "16,498,204", "17,296,885", "17,611,762", "18,239,288", "20,359,883"), class = "factor")), .Names = c("years", "units"), class = "data.frame", row.names = c(NA, -10L))

traffic.data
       years     units
#  1   2008 12,866,461
#  2   2009 13,350,011
#  3   2010 15,361,841
#  4   2011 15,669,918
#  5   2012 15,106,666
#  6   2013 16,498,204
#  7   2014 17,296,885
#  8   2015 17,611,762
#  9   2016 18,239,288
# 10  2017  20,359,883

ggplot(traffic.data, aes(x = years, y = as.numeric(units))) + 
   geom_point() +
   geom_line() +
   scale_x_continuous(breaks = seq(2008, 2017, 1)) + 
   scale_y_continuous(breaks = seq(10000000,30000000,1)) +
   labs(x = "years", y = "total traffic of passengers", 
        title = "evolution of traffic during the past 10 years")

当我 运行 此代码时,我得到以下折线图,缺少 Y 轴的值:

问题一:

scale_y_continuous(breaks = seq(10000000,30000000,1))

因此,您正在尝试将 10M 增加 1 到 30M。

问题二:

  +   labs(x = "years", y = "total traffic of passengers", 
    +        title = "evolution of traffic during the past 10 years")

在这一行中不需要第二个 +,这会产生问题。


这个数据对我来说效果很好

dt<-data.frame(years=c(2008:2018),
               units=sample(c(15000000:20000000),11,replace = T))
dt

和此代码:

       ggplot(dt, aes(x=years, y=units))+
   geom_point(data=NULL)+
   geom_line(data=NULL) + 
   scale_y_continuous(breaks = seq(10000000,30000000,1000000)) + 
   labs(x = "years", y = "total traffic of passengers",
        title = "evolution of traffic during the past 10 years")

结果如下:

数据集

# example dataset
df = structure(list(years = 2008:2017, 
                    units = structure(c(1L, 2L, 4L, 5L, 3L, 6L, 7L, 8L, 9L, 10L), .Label = c("12,866,461", "13,350,011", "15,106,666", "15,361,841", "15,669,918", "16,498,204", "17,296,885", "17,611,762", "18,239,288", "20,359,883"), class = "factor")), 
              .Names = c("years", "units"), class = "data.frame", row.names = c(NA, -10L))

问题

您的 units 列是 factor 并且将其更新为数字很棘手。检查这个:

as.numeric(df$units)
# [1]  1  2  4  5  3  6  7  8  9 10

这些是您在 y 轴上绘制的值。这就是为什么无论实际数字是多少,您的点之间的距离似乎都相同,这就是为什么这些值也没有显示在 y 轴上,因为您指定 scale_y_continuous(breaks = seq(10000000,30000000,1))(即从 3mil 开始)。

解决方案

# update column
df$units = as.numeric(gsub(",", "", as.character(df$units), fixed = TRUE))

library(ggplot2)

ggplot(df, aes(x=years, y=units)) +
  geom_point() +
  geom_line() + 
  scale_x_continuous(breaks = seq(2008,2017,1))+ 
  scale_y_continuous(breaks = seq(10000000,30000000,1000000)) +
  labs(x = "years", y = "total traffic of passengers", title = "evolution of traffic during the past 10 years")

请注意,我已将您的 y 轴值之间的 step/distance 更改为 1mil。 step = 1 会使过程变慢并且情节不可读。

您可以在绘图前使用options(scipen = 999),以避免科学计数法。