Reputation: 463
I have successfully made a dotplot in R using ggplot2 using this code.
data <- data.frame("State" = c("NJ", "NY", "PA", "ND","NJ", "NY", "PA", "ND"), "Year" = c("1985",
"1985", "1985", "1985", "1990", "1990", "1990", "1990"), "DataValue" = c(33, 20, 44, 21, 55, 11, 17,
46))
p <- ggplot(data,aes(x = State, y = DataValue, color = Year)) +
geom_point(data = subset(data, !is.na(DataValue))) +
geom_point(data = subset(data, is.na(DataValue)), color = "pink") +
scale_shape_manual(values=c(4, 17))+
scale_color_manual(values=c("cyan", "blueviolet", "purple", "turquiose4")) +
theme(axis.text.x = element_text(colour = "black"), plot.title = element_text(hjust = 0.5)) +
geom_vline(xintercept = c(3.5)) + labs(title = "DataValues", x = "State/Territory", y = "Value") +
geom_hline(yintercept = 0, color = "grey24")
p<- p + theme(legend.position="bottom")
p
I added the shape_scale_manual to change the shape depending on the year and it is not working. Does anyone have any suggestions on how I can fix this?
Thank you!
Upvotes: 0
Views: 1639
Reputation: 125832
Maybe this what you are looking for:
To make scale_shape_manual work you have to map a variable on shape, i.e. map Year
on shape
.
If you are using different datasets and or aesthetics for the geoms in my opinion it's best to make them local instead of setting them globally in ggplot()
, i.e. move the mapping on color
and shape
into the first geom_point
. This should give you the right colors and shapes.
data <- data.frame("State" = c("NJ", "NY", "PA", "ND","NJ", "NY", "PA", "ND"), "Year" = c("1985",
"1985", "1985", "1985", "1990", "1990", "1990", "1990"), "DataValue" = c(33, 20, 44, 21, 55, 11, 17,
46))
library(ggplot2)
p <- ggplot(mapping = aes(x = State, y = DataValue)) +
geom_point(data = subset(data, !is.na(DataValue)), aes(color = Year, shape = Year)) +
geom_point(data = subset(data, is.na(DataValue)), color = "pink") +
scale_shape_manual(values=c(4, 17))+
scale_color_manual(values=c("cyan", "blueviolet", "purple", "turquiose4")) +
theme(axis.text.x = element_text(colour = "black"), plot.title = element_text(hjust = 0.5)) +
geom_vline(xintercept = c(3.5)) + labs(title = "DataValues", x = "State/Territory", y = "Value") +
geom_hline(yintercept = 0, color = "grey24")
p<- p + theme(legend.position="bottom")
p
Upvotes: 1