我有以下数据:
id <- rep(1:100)
A <- rep(c(0.12 ,0.25, 0.5, 1, 2), each = 20)
B <- rep(c(0.06, 0.03, 0.015, 0.12), each = 25)
C <- rep(c(0.015, 0.03, 0.06, 0.12, 0.25), each = 20)
df <- data.frame(id,A,B,C,stringsAsFactors = F)
我把A,B和C分成两列。请注意,A,B和C列实际上是因素,我只是避免将它们指定为创建小提琴图的因素。
library(dplyr)
df_edited <- df %>%
gather(key, value, -id, factor_key = F)
我用这些数据创建了以下图:
library(ggplot2)
factor_breaks <- c(0.015,0.03,0.06,0.12,0.25,0.5,1,2)
factor_levels <- c("0.015","0.03","0.06","0.12","0.25","0.5","1","2")
ggplot(df_edited, aes(key, value))+
geom_violin()+
scale_y_continuous(labels = factor_levels, breaks = factor_breaks)
是否可以使y轴标签安全放置,如下图所示,并确保小提琴图是否正确?
ggplot(df_edited, aes(key, factor(value)))+
geom_violin()
答案 0 :(得分:3)
一种选择是转换y轴的值
ggplot(df_edited, aes(key, value))+
geom_violin()+
scale_y_continuous(labels = factor_levels,
breaks = factor_breaks,
trans = 'log10')
答案 1 :(得分:1)
虽然log10也可以在这个例子中使用,但我认为更通用到&#34; rescale&#34;使用sapply
:
df_edited$newValue <- sapply(as.character(df_edited$value),
function(x){which(factor_levels == x)})
这基本上返回factors_levels
向量中值的位置。
ggplot(df_edited, aes(key, newValue))+
geom_violin() +
scale_y_continuous(breaks = 1:length(factor_levels),
labels = factor_levels)