如何使用 base R 在小提琴图中添加均值
How to add value of mean in number in violin plot using base R
我有资料
Name V1
M1 50
M2 10
M1 30
M1 45
M2 5
M2 7
使用我的代码,我能够生成 violin plot
。但是我不知道如何使用 base R
(而不是 ggplot
)将每个小提琴图中的均值放在数字中?
这是我的代码示例。
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
plotCentre="line", rectCol="white", col="gray", ylab="",
ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")
非常感谢
您可以使用以下代码:
您的数据:
Data <- read.table(header = TRUE,
text = "Name V1
M1 50
M2 10
M1 30
M1 45
M2 5
M2 7")
代码
library(vioplot)
library(dplyr)
## calculate the mean per group
DataMean <- Data %>%
group_by(Name) %>%
summarize(mean = mean(V1))
## your plotting code
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
plotCentre="line", rectCol="white", col="gray", ylab="",
ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")
## use base r 'text' to add the calculated means
## at position 1 and 2 on the X-axis, and
## at height of the Y-axis of 60 (2 times)
text(x = c(1, 2), y = c(60,60), labels = round(DataMean$mean, 2))
产生以下情节:
当然,我们可以调整文本的位置。如果我们希望均值出现在小提琴图内,我们将均值用作 Y-coordinates,并更改颜色以使其更明显(并将 X-coordinates 向右移动一点,组合浅灰色)。
### playing with position and color
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
plotCentre="line", rectCol="white", col="lightgray", ylab="",
ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")
text(x = c(1.1, 2.1), y = DataMean$mean, labels = round(DataMean$mean, 2), col = "blue")
生成此图:
请告诉我这是否是您想要的。
我有资料
Name V1
M1 50
M2 10
M1 30
M1 45
M2 5
M2 7
使用我的代码,我能够生成 violin plot
。但是我不知道如何使用 base R
(而不是 ggplot
)将每个小提琴图中的均值放在数字中?
这是我的代码示例。
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
plotCentre="line", rectCol="white", col="gray", ylab="",
ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")
非常感谢
您可以使用以下代码:
您的数据:
Data <- read.table(header = TRUE,
text = "Name V1
M1 50
M2 10
M1 30
M1 45
M2 5
M2 7")
代码
library(vioplot)
library(dplyr)
## calculate the mean per group
DataMean <- Data %>%
group_by(Name) %>%
summarize(mean = mean(V1))
## your plotting code
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
plotCentre="line", rectCol="white", col="gray", ylab="",
ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")
## use base r 'text' to add the calculated means
## at position 1 and 2 on the X-axis, and
## at height of the Y-axis of 60 (2 times)
text(x = c(1, 2), y = c(60,60), labels = round(DataMean$mean, 2))
产生以下情节:
当然,我们可以调整文本的位置。如果我们希望均值出现在小提琴图内,我们将均值用作 Y-coordinates,并更改颜色以使其更明显(并将 X-coordinates 向右移动一点,组合浅灰色)。
### playing with position and color
with(Data, vioplot(V1[Name=="M1"], V1[Name=="M2"], names=c("M1", "M2"),
plotCentre="line", rectCol="white", col="lightgray", ylab="",
ylim=c(0,80)))
title(ylab="A($m)", xlab="Name", main="AA")
text(x = c(1.1, 2.1), y = DataMean$mean, labels = round(DataMean$mean, 2), col = "blue")
生成此图:
请告诉我这是否是您想要的。