一个ggplot中包含五个Boxplot。

问题描述 投票:0回答:1

我想在一个ggplot中制作五个时间序列(数据框)的boxplot。这可能吗?

目前我是这样做的,一次做一个,然后我可以用plot_grid把它们并排在一起。

BoxAAPL <- ggplot(oldandnew, aes(y = oldandnew[,2])) + 
  geom_boxplot() +
  xlab("") + 
  ylab("Daily Return %") +
  theme_classic() 

但是否可以把它们都放在一个图中呢?那就是为每个。"AAPL, not cleaned","AAPL, cleaned","GE","SPY","WMT"? 从这里开始 http:/www.sthda.comenglishwikiggplot2-box-plot-quick-start-guide-r-software-and-data-visualization 我可以看到,我应该从数值改为因子,但这对我来说并没有意义。可能因为是时序数据吧?

一个数据样本。

structure(list(Date = structure(c(10960, 10961, 10962, 10963, 
10966), class = "Date"), `AAPL, not cleaned` = c(-8.810021, 1.45281, 
-9.051401, 4.628075, -1.774445), `AAPL, cleaned` = c(-8.810021, 
1.45281, -9.051401, 4.628075, -1.774445), GE = c(-4.08219945, 
-0.17376199, 1.32681098, 3.7986923, -0.03966156), SPY = c(-3.989133, 
0.1787311, -1.620197, 5.645238, 0.3424661), WMT = c(-3.813763, 
-2.360084, 1.391327, 7.280618, -1.841673)), row.names = c(NA, 
5L), class = "data.frame")

我希望你能帮我。

r ggplot2 boxplot multiple
1个回答
1
投票

这很容易做到 ggplotggplot 希望数据中的每一个观测值都能在 data.frame.

这也是以下文件所建议的方法。答案之一 到你之前的一个问题。

因此,我们需要先进行一些数据转换。我们可以使用 pivot_longertidyr 来做这件事,我们可以使用 -Date 选择参数来告诉它,除了选择参数之外,所有列都要进行数据透视。Date. 默认情况下,将列名移至列名栏。name 栏和值到 value.

然后我们告诉 ggplot 将数值按 name 并改变其颜色,在 aes 呼叫。

library(dplyr)
library(tidyr)
library(ggplot2)
oldandnew %>%
  pivot_longer(-Date) %>%
  ggplot(aes(y=value, x=name, fill=name)) +
     geom_boxplot() +
     xlab("") + 
     ylab("Daily Return %") +
     theme_classic() 

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.