首页 > 解决方案 > 在小提琴图中表示点

问题描述

以下代码绘制了一个小提琴图表,其中权重与值相关联。问题是,为什么只显示一个点?顶部是218*1=218,因此显示了 218 处的一个点,这很好。但是,对于第二个和第三个,预计会在218*0.1=21.8和处看到两个点30*0.9=27

> library(ggplot2)
> mydata <- read.csv('test.csv', header=T,row.names=1)
> mydata
       V1  V2 V3
P1.K1 218 1.0  R
P2.K1 218 0.1  R
P2.K2  30 0.9  R
> p <- ggplot(mydata, aes(x=V3, y=V1, weight=V2)) + geom_violin(trim=FALSE)
> p + geom_dotplot(binaxis='y', stackdir='center', dotsize=1)
`stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
>

在此处输入图像描述

有什么想法吗?

标签: rggplot2violin-plot

解决方案


在Waldi 的帮助下更新,现在它应该可以工作了。

这里的主要内容是为其分配加权值,geom_dotplot 这将仅用一个点来解决 Op 的问题。

library(ggplot2)

#  add V1_weight to mydata
mydata <- mydata %>% 
  mutate(V1_weight= V1*V2)

ggplot(mydata) + 
  geom_violin( mapping = aes(x = V3, y = V1, weight = V2),trim=FALSE) +
  geom_dotplot(aes(x = V3, y=V1_weight), binaxis='y', stackdir='center', dotsize=1) 

在此处输入图像描述

数据:

structure(list(id = c("P1.K1", "P2.K1", "P2.K2"), V1 = c(218, 
218, 30), V2 = c(1, 0.1, 0.9), V3 = c("R", "R", "R"), V1_weight = c(218, 
21.8, 27)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", 
"data.frame"))

推荐阅读