繁体   English   中英

多个分布图(不同的变量)作为同一图中的方面

[英]multiple distribution plots (different variables) as facets in the same plot

我想将不同变量的分布图放入一个图像文件中。 每个分布图(子图)都包含由颜色分隔的相似组。

目前我正在使用 ggplot 分别绘制每个变量。 然后我使用 grid.arrange 将所有子图组合在一起,我可以代表所有分布。

(以下示例代码)

#plot1
plot_min_RTT <- ggplot(house_total_year, aes(x=min_RTT,  colour = ISP)) +
geom_density(adjust = 1/2,alpha=0.1, size = 2) 

#plot2
plot_MaxMSS <- ggplot(house_total_year, aes(x=MaxMSS,  colour = ISP)) +
geom_density(adjust = 1/2,alpha=0.1, size = 2) 

#plot3
plot_send_buffer_size <- ggplot(house_total_year, aes(x=send_buffer_size,  colour = ISP)) +
geom_density(adjust = 1/2,alpha=0.1, size = 2) 

#plot4
plot_maxSpeed <- ggplot(house_total_year_filtered, aes(x=download_speed_max_month,  colour = ISP)) +
geom_density(adjust = 1/2,alpha=0.1, size = 2) 

#combine
grid.arrange(plot_min_RTT,plot_MaxMSS,plot_send_buffer_size,plot_maxSpeed)

可以看出,每个子图的 x 轴使用的变量是不同的。 但都有相似的分组变量(ISP)。 我最终得到了下面的一个情节:

我目前拥有的

但是,我真正想要的是所有子图只有一个图例(ISP)。 我正在考虑使用 ggplot 中的 facet_wrap 函数,但我仍在为此苦苦挣扎。 请帮忙。

任何建议将不胜感激!

谢谢! :)

您没有提供可重现的数据,因此我使用了 ggplot 包附带的 data.frame mpg

# Subset the data
d <- mpg[, c(1, 3:5)]
# your ISP == manufacturer
# Than transform the data to long format as stated already in the comments using reshape function melt
library(reshape2)
d_long <- melt(d)
head(d_long)
  manufacturer variable value
1         audi    displ   1.8
2         audi    displ   1.8
3         audi    displ   2.0
4         audi    displ   2.0
5         audi    displ   2.8
6         audi    displ   2.8

# Now plot the data using the variable column in facet_grid for the layout.
# scales = "free_x" is used for vairable dependend x-axis scales. 
ggplot(d_long, aes(x = value, colour = manufacturer)) + 
  geom_density() + 
  facet_grid( ~ variable, scales = "free_x") + 
  theme_bw()

出:

在此处输入图片说明

# Instead of using facet_grid you can try 
# facet_wrap( ~ variable, scales = "free_x", ncol = 2) 
# to arrange the plots row- and colwise as your needs are. The scaling of both axis can also changed. 
ggplot(d_long, aes(x = value, colour = manufacturer)) + 
  geom_density() + 
  facet_wrap( ~ variable, scales = "free", ncol = 2) + 
  theme_bw()

出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM