【发布时间】:2019-08-27 15:21:40
【问题描述】:
我尝试用 ggplot2 绘制 1845-1848 年每个农业年度法国的月度小麦价格。我得到了下表:
year,January,February,March,April,May,June,July,August,September,October,November,December
1845,,,,,,,,20.17,20.3,21.51,22.27,22.32
1846,22.36,22.65,22.42,22.26,22.48,22.93,22.92,24,24.9,25.97,27.59,28.01
1847,30.16,33.5,37.69,37.54,37.98,33.5,28.42,23.63,22.57,22.01,20.76,20.36
1848,20.01,19.34,18.12,16.59,16.58,15.88,15.67,,,,,
我想用以下方式用线和点绘制数据:
- x 为月份,y 为价格
- 按年分组:每年有自己的一行(四行)
- 没有数据 (NA) 的地方应该没有点和线
这个任务在 libreoffice calc 中非常容易解决,只需点击几下:选择所有表格 > 插入图表 > 线 > 点和线 > 下一个 > 数据系列在行中 + 第一行作为标签 + 第一列作为标签 > 完成(8 次点击)。
但我似乎找不到使用 R 和 ggplot2 来做同样事情的方法。
我需要能够在 R 中解决这个问题,以便对系列应用进一步的统计分析。
我尝试了以下解决方案:
# Reading the data
wheat <- read_csv("data/wheat.csv")
# Plotting
wheat %>%
ggplot(aes(x=wheat[0,])) +
geom_line(aes(y=as.numeric(wheat[1,]), group="year")) +
geom_point()
我认为这样的代码会产生所需的情节。
但我得到了错误
"不知道如何自动选择对象类型的比例 tbl_df/tbl/data.frame。默认为连续。错误:美学 长度必须为 1 或与数据 (4) 相同:y, x"。
我知道 ggplot 看到一个 4x13 的小标题并等待 y 具有相同的长度 (4)。
但我想将表格行作为 y 值提供给他。
感谢您的帮助!
编辑
我的问题不是“Constructing a line graph using ggplot2”的重复。
虽然这是相同的一般问题 - 绘制一个数据帧的多个向量并准备数据以供 ggplot 使用 - 初始数据非常不同:我的是必须按时间顺序组织的历史数据,因此需要指定将在 x 上组织数据的levels。加上初始表是特殊的,需要与gather 进行特殊处理。
这里是整个工作代码供参考:
library(tidyverse)
# Reading into a tibble:
wheat <- read_csv("year,January,February,March,April,May,June,July,August,September,October,November,December
1845,,,,,,,,20.17,20.3,21.51,22.27,22.32
1846,22.36,22.65,22.42,22.26,22.48,22.93,22.92,24,24.9,25.97,27.59,28.01
1847,30.16,33.5,37.69,37.54,37.98,33.5,28.42,23.63,22.57,22.01,20.76,20.36
1848,20.01,19.34,18.12,16.59,16.58,15.88,15.67,,,,,")
# Tidying:
wheat_tidy <- wheat %>% gather(month, price, -year)
# Leveling:
wheat_tidy$month <- factor(wheat_tidy$month, levels = c("January","February","March","April","May","June","July","August","September","October","November","December"))
# Plotting:
wheat_tidy %>%
ggplot(aes(x=month, y=price, group=year, color=as.factor(year))) +
geom_line() +
geom_point()
【问题讨论】:
-
相关/可能重复:Stacked Bar Plot in R
-
您需要将数据从宽格式更改为长格式。您可以使用
dplyr::gather执行此操作:df %>% gather(month,value,-year,factor_key = T) %>% ggplot(aes(month,value,group=factor(year),colour=factor(year))) + geom_line() + geom_point()