一个 ggplot 中的五个箱线图
Five Boxplots in one ggplot
我想在一个 ggplot 中制作五个时间序列(数据框)的箱线图。那可能吗?
到目前为止,我就是这样做的,一次制作一个,然后我可以将它们与 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.com/english/wiki/ggplot2-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")
希望你能帮帮我。
使用 ggplot
很容易做到这一点,但是 ggplot
期望数据在 data.frame
的它自己的行上有每个观察值。
这与 针对您之前的一个问题推荐的方法相同。
因此,我们需要先做一些数据转换。我们可以使用 tidyr
中的 pivot_longer
来执行此操作,我们可以使用 -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()
我想在一个 ggplot 中制作五个时间序列(数据框)的箱线图。那可能吗?
到目前为止,我就是这样做的,一次制作一个,然后我可以将它们与 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.com/english/wiki/ggplot2-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")
希望你能帮帮我。
使用 ggplot
很容易做到这一点,但是 ggplot
期望数据在 data.frame
的它自己的行上有每个观察值。
这与
因此,我们需要先做一些数据转换。我们可以使用 tidyr
中的 pivot_longer
来执行此操作,我们可以使用 -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()