r - 如何在 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")
解决方案
问题在于数据的格式应该是长格式而不是宽格式,这是使用 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")
推荐阅读
- powershell - How do i dynamically change file-names with Rename-Item?
- javascript - fs.readFileSync("./bank/"+client,'cp1251'); 正在抛出新的 ERR_INVALID_OPT_VALUE_ENCODING
- c# - 如何从 ObjectListView 中选定项目的特定列中获取数据?
- vba - 运行时错误 91,未设置对象,尝试自动下载电子邮件附件
- vb6 - 将 BLOB 保存到文档
- javascript - 在第一个结果中获取下拉列表的返回值 [object Object]。当我选择一个选项并工作时,它会改变。如何修复默认结果
- laravel - 部署 laravel + vuejs 到共享主机
- java - 使用 PreparedStatement 在 where 子句中传递字符串
- mysql - 加入两个集合并在 MongoDB 中更新
- c - libxml2 的解析问题:命名空间错误