R 如何使用ggplot从一个数据帧绘制多行?

R 如何使用ggplot从一个数据帧绘制多行?,r,ggplot2,R,Ggplot2,我试图用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.0

我试图用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()
这里有三个问题:

1您的数据不整齐,这意味着月份不是一个变量。这只是一个列名。您可以使用gather来帮助实现这一点

2在您的第一个aes语句中,您需要定义x和y

3.仅仅用组来定义年份没有多大帮助;您仍然需要定义组中的每个值如何不同-例如,使用颜色使每一年的线条具有不同的颜色

这段代码为我工作编辑:类似于上面kstew的评论,这是在我写答案时发布的:

library(tidyverse) #includes ggplot

wheat <-read_delim("year,January,February,March,April,May,June,July,August,September,October,November,December\n1845,,,,,,,,20.17,20.3,21.51,22.27,22.32\n1846,22.36,22.65,22.42,22.26,22.48,22.93,22.92,24,24.9,25.97,27.59,28.01\n1847,30.16,33.5,37.69,37.54,37.98,33.5,28.42,23.63,22.57,22.01,20.76,20.36\n1848,20.01,19.34,18.12,16.59,16.58,15.88,15.67,,,,,", delim = ",")

df <- wheat %>%
  gather(theMonth, wheatValue, -year)

plot <- ggplot(df, aes(x = theMonth, y = wheatValue, group = as.factor(year), color = as.factor(year))) +
  geom_line()

相关/可能重复:您需要将数据从宽格式更改为长格式。您可以使用dplyr::gather执行以下操作:df%>%gathermonth,value,-year,factor_key=T%>%ggplotaesmonth,value,group=factoryear,color=factoryear+geom_line+geom_point可能与伟大的@mmyoung77重复!在手工整理excel中的数据后,我能够得到相同的图。现在,您已经向我展示了如何使用gather执行相同的操作,谢谢!但是结果图是错误的:x轴应该按时间顺序排列月份,在这里,它们的顺序很奇怪,因此线条是错误的。有没有关于如何修正x轴顺序的线索?好的,这似乎是我的排序问题的答案。ggplot2订单默认情况下,可以按字母数字进行更改。由于缺少数据,as.factor可能会将月份按错误的顺序排列。我确实需要使用wheat_tidy$month将月份名称显式影响为级别感谢@mmyoung77,感谢您的工作解决方案!同时感谢两位评论者的建议。非常感谢!
library(tidyverse) #includes ggplot

wheat <-read_delim("year,January,February,March,April,May,June,July,August,September,October,November,December\n1845,,,,,,,,20.17,20.3,21.51,22.27,22.32\n1846,22.36,22.65,22.42,22.26,22.48,22.93,22.92,24,24.9,25.97,27.59,28.01\n1847,30.16,33.5,37.69,37.54,37.98,33.5,28.42,23.63,22.57,22.01,20.76,20.36\n1848,20.01,19.34,18.12,16.59,16.58,15.88,15.67,,,,,", delim = ",")

df <- wheat %>%
  gather(theMonth, wheatValue, -year)

plot <- ggplot(df, aes(x = theMonth, y = wheatValue, group = as.factor(year), color = as.factor(year))) +
  geom_line()