Reputation: 1041
I have the following data:
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)
I gather A,B, and C into two columns. Note that column A, B and C are actually factors, I just avoid specifying them as factors to create the violin plot.
library(dplyr)
df_edited <- df %>%
gather(key, value, -id, factor_key = F)
I create the following plot with this data:
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)
This creates the following plot:
Is it possible to make the y-axis labels to be safely placed evenly, as in the plot below, and still make sure that the violin-plot is correct?
ggplot(df_edited, aes(key, factor(value)))+
geom_violin()
Upvotes: 5
Views: 1300
Reputation: 10350
While log10 would also work in this example, I think it is more generic to "rescale" the values using sapply
:
df_edited$newValue <- sapply(as.character(df_edited$value),
function(x){which(factor_levels == x)})
This basically returns the position of the values within the factors_levels
vector.
ggplot(df_edited, aes(key, newValue))+
geom_violin() +
scale_y_continuous(breaks = 1:length(factor_levels),
labels = factor_levels)
Upvotes: 2
Reputation: 26343
One option is to transform the values of the y-axis
ggplot(df_edited, aes(key, value))+
geom_violin()+
scale_y_continuous(labels = factor_levels,
breaks = factor_breaks,
trans = 'log10')
Upvotes: 4