Yuriy Grabovsky
Yuriy Grabovsky

Reputation: 171

ggplot apply different scaling to parts of axis for continuous variable

I'm trying to make an age distribution comparison between groups in ggplot in R and what I'd like to do is emphasize specific age groups by making that part of the axis wider:

graph example

Here, I'd like to expand the 0, 6, 12, 24, 36 range to be wider, but reduce the length of the 60, 120 etc tail so it's not as long.

Code I'm using:

require(ggplot2)
p <- ggplot(age.df, aes(x=group, y=Age.cont, fill=group)) + 
geom_violin(trim=TRUE) + geom_boxplot(width=0.05, colour = "#FFFFFF", 
outlier.shape = NA) + 
scale_fill_manual(values=rev(c("#83141F", "#1F427D", "#036A3C"))) +
scale_colour_manual(values="#FFFFFF") + theme_classic() +
xlab("") + ylab("Age (months)") + scale_y_continuous(breaks = c(0, 6, 12, 24, 
36, 48, 60, 120))

p + coord_flip()

Any help is appreciated

Upvotes: 0

Views: 124

Answers (1)

Dan
Dan

Reputation: 12074

You could use a square root transform. You don't provide data, so I created my own data frame for this example.

# Dummy data frame
df <- data.frame(values = runif(100, 0, 120),
                 groups = c(rep("A", 50), rep("B", 50)))

# Create violin plot with square root transform
ggplot(df, aes(x = groups, y = values)) + 
  geom_violin() + 
  coord_flip() +
  scale_y_sqrt(breaks = c(0, 6, 12, 24, 36, 48, 60, 120))

enter image description here

Upvotes: 2

Related Questions