首页 > 解决方案 > 如何在 r 中使用 ggplot2 包进行绘图

问题描述

我需要使用ggplot2包在 r 中绘制数据框。数据框df有多个列,分别是日期、col1、col2、col3 等。我使用以下代码进行绘图,没有报告错误消息,但没有绘图出来。我试过show(p)了,它也不起作用。谁能告诉这里有什么问题。谢谢。

library(ggplot2)
p <-
  ggplot(df) +
  geom_line(aes(Date,col1)) +
  geom_line(aes(Date,col2), col='red') + 
  labs(y="cost", title="PLOT")
print(p)

这是我使用的数据。

         Date     col1   col2  col3
1 2011-01-01   718.8011  100   861.9
2 2011-01-02   777.9102  100   861.9
3 2011-01-03   856.4745  100   861.9
4 2011-01-04   626.4703  100   861.9

输入

structure(list(Date = c("2011-01-01", "2011-01-02", "2011-01-03", 
"2011-01-04"), col1 = c(718.8011, 777.9102, 856.4745, 626.4703
), col2 = c(100L, 100L, 100L, 100L), col3 = c(861.9, 861.9, 861.9, 
861.9)), row.names = c(NA, -4L), class = "data.frame")

标签: rggplot2

解决方案


问题在于数据的格式应该是长格式而不是宽格式,这是使用 tidyr 包解决此问题的方法;

library(dplyr)
library(ggplot2)
library(tidyr)

df <-
  data.frame(
    Date = as.Date(c("2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04")),
    col1 = c(718.8011, 777.9102, 856.4745, 626.4703),
    col2 = c(100, 100, 100, 100),
    col3 = c(861.9, 861.9, 861.9, 861.9)
  )

df %>%
  gather(key = "Col", value = "value", -Date) %>%
  ggplot(aes(Date, value, colour = Col)) +
  geom_line() + 
  labs(y = "cost", title = "PLOT")

在此处输入图像描述


推荐阅读