使用ggplot2渐变填充小提琴图 [英] gradient fill violin plots using ggplot2

查看:2074
本文介绍了使用ggplot2渐变填充小提琴图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据箱内点的密度(蓝色表示最高密度,红色表示最低)梯度填充小提琴图。



我使用以下命令生成了一个图表,但未能根据密度对其进行着色(本例中为小提琴的宽度),我也希望生成箱形图

 库(ggplot2)
数据(钻石)

ggplot(diamonds,aes(x = cut,y = carat))+ geom_violin()


解决方案

改变使用fill =变量的小提琴情节的颜色,如下所示:

  ggplot(钻石,aes(x = cut,y = carat))+ geom_violin(aes(fill = cut))



$ p
$ b

  ggplot(diamonds,aes(x = cut,y = carat))+ geom_boxplot( aes(fill = cut))

p>

但是无论你有什么价值,都必须具有相同的价值对于每一次剪裁,也就是说,如果您想使用平均深度/剪裁作为颜色变量,您必须对其进行编码。



用dplyr将您的钻石分组(或任何其他变量)

  library(dplyr)
diamonds_group< - group_by(diamonds,cut)
diamonds_group< - summary(diamonds_group,Mean_Price = mean(price))


$ b $然后,我使用diamonds2作为钻石的副本,然后操作数据集。b
$ b

  diamonds2 < -  diamonds 

我将两个数据框合并在一起,将Mean_Depth作为菱形块中的变量获得2

  diamonds2 < -  merge(diamonds2,diamonds_group)



<现在我可以用平均深度作为一个颜色变量来绘制它。

  ggplot(diamonds2,aes(x = cut,y = carat))+ geom_boxplot(aes(fill = Mean_Price))+ scale_fill_gradient2(midpoint = mean(diamonds2 $ pric e))


I want to gradient fill a violin plot based on the density of points in the bins (blue for highest density and red for lowest).

I have generated a plot using the following commands but failed to color it based on density (in this case the width of the violin. I also would like to generate box plots with similar coloring).

library("ggplot2")
data(diamonds)

ggplot(diamonds, aes(x=cut,y=carat)) + geom_violin() 

解决方案

to change the colour of the violin plot you use fill = variable, like this:

ggplot(diamonds, aes(x=cut,y=carat)) + geom_violin(aes(fill=cut)) 

same goes for boxplot

ggplot(diamonds, aes(x=cut,y=carat)) + geom_boxplot(aes(fill=cut)) 

but whatever value you have has to have the same value for each cut, that is, if you wanted to use for example mean depth/cut as the color variable you would have to code it.

with dplyr group your diamonds by cut and with summarize get the mean depth (or any other variable)

library(dplyr)
diamonds_group <- group_by(diamonds, cut)
diamonds_group <- summarize(diamonds_group, Mean_Price = mean(price))

Then I used diamonds2 as a copy of diamonds to then manipulate the dataset

diamonds2 <- diamonds

I merge both dataframes to get the Mean_Depth as a variable in diamonds2

diamonds2 <- merge(diamonds2, diamonds_group)

And now I can plot it with mean depth as a color variable

ggplot(diamonds2, aes(x=cut,y=carat)) + geom_boxplot(aes(fill=Mean_Price)) + scale_fill_gradient2(midpoint = mean(diamonds2$price))

这篇关于使用ggplot2渐变填充小提琴图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆