r - ggplot2 代码运行并更新绘图,但实际上没有显示数据

标签 r plot ggplot2

我正在尝试在 R 中使用 ggplot2 生成图表。虽然我能够使用 plot() 以及运行 ggplot 时生成我想要的图表下面的代码显示了正确的轴,但没有数据或比例。

数据看起来像这样:

data <- data.frame(area=c("alpha", "alpha", "bravo", "bravo", "charlie", "charlie"),
                   year=c(2001, 2002, 2001, 2002, 2001, 2002),
                   rate=c(.94, .90, .83, .87, .87, .95))

其中面积是字符变量,年份/比率只是数字。

如果我运行

plot(data$year, data$rate)

我在绘图窗口中得到了我期望看到的图表。我想做的就是在 ggplot 中将其重新创建为折线图。这是我尝试过的:

gg <- ggplot(data=data, aes(x="year", y="rate", group="area"))
gg + geom_point()
gg + geom_line()
gg

# also tried subsetting to remove the group issue, thinking that might help but it didn't. also removed line from this too
temp <- data[data$area=="alpha",]
gg <- ggplot(data=temp, aes(x="year", y="rate"))
gg + geom_point()
gg

# also tried this which manages to put a dot in the middle of the still empty plot
ggplot(data=test) +
     geom_point(mapping=aes(x="Year", y="Attendance Rate", group="Area"))

在这两种情况下,我都得到相同的结果:代码运行良好(无错误)并且绘图窗口刷新到我最近使用的那个,但是虽然它有正确的 X 和 Y 标签(年份/比率),但它没有实际上并没有把数据放在那里。也没有刻度,因此显然它不会读取其中的信息。

我在这里做错了什么?我一直在使用下面的指南和引用表,但我(至少想认为我)正在正确地重新创建它们,但显然我没有。

https://www.rstudio.com/wp-content/uploads/2016/11/ggplot2-cheatsheet-2.1.pdf

http://r-statistics.co/ggplot2-cheatsheet.html

http://www.sthda.com/english/wiki/ggplot2-line-plot-quick-start-guide-r-software-and-data-visualization

http://tutorials.iq.harvard.edu/R/Rgraphics/Rgraphics.html

最佳答案

不要使用引号。
使用:aes("year", "rate"),您绘制了单词"year""rate"
使用aes(year,rate),您可以在数据data中绘制变量yearrate

ggplot(data, aes(year, rate, group = area)) + 
    geom_point() + 
    geom_line()

enter image description here

如果由于某种原因您必须使用引号,则使用 aes_string相反:

ggplot(data, aes_string("year", "rate", group = "area")) + 
    geom_point() + 
    geom_line()

关于r - ggplot2 代码运行并更新绘图,但实际上没有显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346657/

相关文章:

r - 在 R 直方图中作为参数 'breaks' 传递的单个数字意味着什么?

r - 如何使用 devtools 和备用 gcc 安装?

python - 如何在 Python 中使用 Matplotlib 绘制阶跃函数?

r - gganimate 绘图,其中点保留而线淡出

r - 如何根据 R 中的条件从数据框中删除行?

r - ggplot2 的奇怪行为

r - 维恩图 : How to hide % overlap labels?

python - 如何使条形图自动循环显示不同颜色?

r - 在 ggplot 上显示 x 轴的特定值

R:ggplot2 图例未显示