首页 > 解决方案 > R中的几个返回绘图

问题描述

尝试在 R 中绘制非常基本的数据。

Year    X1     X2     X3     X4     X5     X6     X7
2004   0.91   0.23   0.28   1.02   0.90   0.95   0.94  
2005   0.57   -0.03  0.88   0.52   0.47   0.55   0.56  
2006   1.30   -0.43  1.95   1.27   1.00   1.19   1.26  
2007   0.44   0.63   0.60   0.34   0.60   0.50   0.46  
2008   1.69   0.34  -2.81  -2.41  -1.80  -1.87  -1.83 

我正在寻找的是随着时间推移的基本折线图,x = year并且y = value图表本身应该包括所有X1- X7

我正在查看ggplot2功能,但我不知道从哪里开始。

# Libraries
library(tidyverse)
library(streamgraph)
library(viridis)
library(plotly)

# Plot
p <- data %>% 
  ggplot(aes(x = year, y = n) +
    geom_area() +
    scale_fill_viridis(discrete = TRUE) +
    theme(legend.position = "none") +
    ggtitle("multiple X over time") +
    theme_ipsum() +
    theme(legend.position = "none")
ggplotly(p, tooltip = "text")

请有人帮我解决一下吗?有没有一种简单的方法可以在基本 R 中做到这一点?

谢谢。

标签: rggplot2

解决方案


目前尚不清楚您打算做什么,geom_area但在下面您将看到您显示的数据的基本折线图。

关键是 'ggplot2' 适用于tidy data,因此您需要首先将数据转换为长格式:

data %>%
    pivot_longer(-Year, names_to = 'Vars', values_to = 'Values') %>%
    ggplot() +
    aes(x = Year, y = Values, color = Vars) +
    geom_line()

在此处输入图像描述


推荐阅读