Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make grouping tighter on ggplot2 geom_jitter?

Attempting to repurpose code for political survey I found on reddit for much smaller sample size.

I am creating a scatterplot using geom_jitter. Here is my code:

ggplot(sae, aes(Alignment, Abortion))+
geom_jitter(aes(color = "green"), size = 4, alpha = 0.6)+
labs("Alignment", "Stance on Abortion")

Here is the graph it gives:enter image description here

How do I make the grouping around the "Pro-choice" or the "Pro-life" lines tighter? I believe this current graph would confuse many people as to which observations are pro-choice or pro-life.

Extra credit for helping with the color problem.

like image 831
Nick Chandler Avatar asked Oct 15 '25 16:10

Nick Chandler


1 Answers

You have a bigger problem. The x-axis is ordered alphabetically, which is very confusing and probably not what you intended. Also, you probably need to specify both the width (jitter in x-direction) and height (jitter in y direction).

You can fix the ordering using, e.g.,

sae$Alignment <- factor(sae$Alignment, levels=unique(sae$Alignment))

as demonstrated below.

# make up some data - you have this already
set.seed(1)     # for reproducible example
sae <- data.frame(Alignment=rep(c("Left","Left Leaning","Center","Right Leaning","Right"),each=5),
                  Abortion =sample(c("Pro Choice","Pro Life","Other"),25, replace=TRUE))

# you start here...
library(ggplot2)
sae$Alignment <- factor(sae$Alignment, levels=unique(sae$Alignment))
ggplot(sae, aes(Alignment, Abortion))+
  geom_point(color = "green", size = 4, alpha = 0.6, position=position_jitter(width=0.1, height=0.1))+
  labs("Alignment", "Stance on Abortion")

Also, IMO, you could do better viz. colors:

sae$Orientation <- with(sae,ifelse(grepl("Left",Alignment),"Progressive",
                                   ifelse(grepl("Right",Alignment),"Conservative","Neutral")))
ggplot(sae, aes(x=Alignment, y=Abortion, color=Orientation))+ 
  geom_point(size = 4, alpha = 0.6, position=position_jitter(width=0.1, height=0.1))+
  labs("Alignment", "Stance on Abortion")

like image 115
jlhoward Avatar answered Oct 17 '25 06:10

jlhoward