我尝试获取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")
答案 0 :(得分:2)
问题1:
scale_y_continuous(breaks = seq(10000000,30000000,1))
因此,您正尝试从1千万增加到30百万。
问题2:
+ 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")
这是结果:
答案 1 :(得分:1)
数据集
# 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轴值之间的步长/距离更改为1mil。步长= 1将使处理过程变慢,并且绘图不可读。
在绘制之前,您可以使用options(scipen = 999)
,以避免用科学的数字表示法。