【发布时间】:2020-07-19 20:27:44
【问题描述】:
我有这些xy 数据,我正在使用R 的ggplot2 geom_violin 进行绘图:
library(dplyr)
library(ggplot2)
set.seed(1)
df <- data.frame(value = c(rnorm(500,8,1),rnorm(600,6,1.5),rnorm(400,4,0.5),rnorm(500,2,2),rnorm(600,7,0.5),rnorm(500,3,1),rnorm(500,3,1)),
age = c(rep("d3",500),rep("d8",600),rep("d24",400),rep("d3",500),rep("d24",600),rep("d8",500),rep("d24",500)),
group = c(rep("A",1500),rep("B",1100),rep("C",1000))) %>%
dplyr::mutate(time = as.integer(age)) %>%
dplyr::arrange(group,time) %>%
dplyr::mutate(group_age=paste0(group,"_",age))
df$group_age <- factor(df$group_age,levels=unique(df$group_age))
ggplot(df,aes(x=group_age,y=value,fill=age,color=age)) +
geom_violin(alpha=0.5) + geom_boxplot(width=0.1,aes(fill=age,color=age,middle=mean(value))) +
theme_minimal()
这给出了:
现在我想将 x-axis ticks 更改为 group tick labels 在每个 group 下方居中。
假设:
ggplot_build(ggplot(df,aes(x=group_age,y=value,fill=age,color=age)) +
geom_violin(alpha=0.5) + geom_boxplot(width=0.1,aes(fill=age,color=age,middle=mean(value))) +
theme_minimal())$data[[2]]$xid
给出我使用的x-axis 位置scale_x_discrete 在breaks 中指定每个group 的中点:
ggplot(df,aes(x=group_age,y=value,fill=age,color=age)) +
geom_violin(alpha=0.5) + geom_boxplot(width=0.1,aes(fill=age,color=age,middle=mean(value))) +
scale_x_discrete(breaks=c(2,4.5,6.5),labels=c("A","B","C")) + theme_minimal()
尝试scale_x_continuous 而不是scale_x_discrete 会出现此错误:
Error: Discrete value supplied to continuous scale
知道如何让x-axis ticks 位于:
c(2,4.5,6.5)
有了这些labels:
c("A","B","C")
【问题讨论】:
-
你不能有
x=group,并按照此处所述修复躲避:Align violin plots with dodged box plots -
致@Henrik - 我不想因为我想在每个
group中添加lmregression行,使用:geom_smooth(data=df,mapping=aes(x=group_age,y=value,group=group),color="black",method='lm',size=1,se=T),这不适用于@987654356 @想法 -
致@Peter——你指的是那篇文章的哪一部分?它比较长。但我宁愿避免
facets -
好的,但是当您的 x 轴似乎是离散的时,我发现拟合回归线有点奇怪,还是我误解了?
-
你的时间变量全部为空。
标签: r ggplot2 axis-labels