0

This is my dataframe:

df = data.frame(info=1:30, type=c(replicate(5,'A'), replicate(5,'B')), group= c(replicate(10,'D1'), replicate(10,'D2'), replicate(10,'D3')))

I want to make a jitter plot of my data distinguished by group (X-label) and type (colour):

ggplot()+
  theme(panel.background=element_rect(colour="grey", size=0.2, fill='grey100'))+
  geom_jitter(data=df, aes(x=group, y=info, color=type, shape=type), position=position_dodge(0.2), cex=2)+
  scale_shape_manual(values=c(17,15,19))+
  scale_color_manual(values=c(A="mediumvioletred", B="blue"))

enter image description here

How can I reduce the distance between the X-labels (D1, D2, D3) in the representation?

P.D. I want to do it even if I left a blank space in the graphic

Gero
  • 107
  • 1
  • 8

3 Answers3

3

Here are a few options.

# Setting up the plot
library(ggplot2)

df <- data.frame(
  info=1:30, 
  type=c(replicate(5,'A'), replicate(5,'B')), 
  group= c(replicate(10,'D1'), replicate(10,'D2'), replicate(10,'D3'))
)

p <- ggplot(df, aes(group, info, colour = type, shape = type))

Option 1: increase the dodge distance. This won't put the labels closer, but it makes better use of the space available so that the labels appear less isolated.

p +
  geom_point(position = position_dodge(width = 0.9))

Option 2: Expand the x-axis. Increasing the expansion factor from the default 0.5 to >0.5 increases the space at the ends of the axis, putting the labels closer.

p +
  geom_point(position = position_dodge(0.2)) +
  scale_x_discrete(expand = c(2, 0))

Option 3: change the aspect ratio. Depending on the plotting window size, this also visually puts the x-axis labels closer together.

p + 
  geom_point(position = position_dodge(0.2)) +
  theme(aspect.ratio = 2)

Created on 2021-06-25 by the reprex package (v1.0.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63
2

The simplest solution is to resize the plot. For example if you follow your command with ggsave("my_plot.pdf", width = 3, height = 4.5) it looks like this:

enter image description here

Or in an Rmd file you can control the dimensions by various means: see this link.

Andy Eggers
  • 592
  • 2
  • 10
2

Try adding coord_fixed(ratio = 0.2) and play around with the ratio.

ggplot()+
  theme(panel.background=element_rect(colour="grey", size=0.2, fill='grey100'))+
  geom_jitter(data=df, aes(x=group, y=info, color=type, shape=type), position=position_dodge(0.2))+
  scale_shape_manual(values=c(17,15,19))+
  scale_color_manual(values=c(A="mediumvioletred", B="blue")) + coord_fixed(ratio = 0.2)

enter image description here

user438383
  • 5,716
  • 8
  • 28
  • 43