使用iris
数据:
require(ggplot2)
ggplot(iris, aes(Species, Sepal.Length)) +
geom_violin(draw_quantiles = c(0.25, 0.5, 0.75))
如何保持平均直线,但使用虚线代替其他两个分位数?
我在@ jan-glx中使用了非常方便的函数来获取我自己的数据:Split violin plot with ggplot2,但老实说我并不理解这段代码中的所有内容。根据这个链接https://seaborn.pydata.org/generated/seaborn.violinplot.html,它似乎在python中是自动的,但我只与R合作。
如果我计算一下:
ggplot(iris, aes(Species, Sepal.Length)) +
geom_violin(draw_quantiles = c(0.25, 0.5, 0.75),
linetype = "dashed")
感谢您的帮助
答案 0 :(得分:1)
我和你有同样的问题。这样做可能不是最优雅的方法,但我先绘制了虚线,然后用fill="transparent"
重新绘制了小提琴。
您可以控制在draw_quantiles
中为geom_violin()
指定的向量中绘制哪些四分位数。首先用虚线画出25和75%的四分位数,然后用仅50%的四分位数和实线重新绘制小提琴。请注意,四分位数的50%代表中位数,而不是平均值。
代码如下:
ggplot(iris, aes(Species, Sepal.Length)) +
geom_violin(draw_quantiles = c(0.25, 0.75),
linetype = "dashed") +
geom_violin(fill="transparent",draw_quantiles = 0.5)
要获取实际均值,必须使用stat_summary()
,但要得到一条直线而不是一条直线。
ggplot(iris, aes(Species, Sepal.Length)) +
geom_violin(draw_quantiles = c(0.25, 0.75),
linetype = "dashed") +
geom_violin(fill="transparent",draw_quantiles = 0.5) +
stat_summary(fun.y=mean, geom="point", shape=20, size=7, color="red", fill="red")