ggplot2 dotplot添加scale_shape_manual不起作用

问题描述

我已使用此代码使用ggplot2在R中成功制作了一个点图。

data <- data.frame("State" = c("NJ","NY","PA","ND","NJ","ND"),"Year" = c("1985","1985","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

添加了shape_scale_manual来根据年份更改形状,但它不起作用。 有人对我如何解决此问题有任何建议吗?

谢谢!

解决方法

也许这就是您要寻找的东西

  1. 要进行scale_shape_manual工作,您必须在形状上映射变量,即在Year上映射shape

  2. 在我看来,如果您对几何使用不同的数据集和/或美学,最好将它们设为局部,而不是在ggplot()中进行全局设置,即,将映射移至color上, shape进入第一个geom_point。这应该为您提供正确的颜色和形状。

data <- data.frame("State" = c("NJ","NY","PA","ND","NJ","ND"),"Year" = c("1985","1985","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