当使用ggplot R时,形状出现填充而不是空心

时间:2016-05-07 21:36:13

标签: r ggplot2

我有一个问题我正在使用ggplot根据我的数据中的3个diffrnet因子制作3个散点图(1997,2002,2007) 这是代码

 countries_data <- read.delim("D:/Rdirectory/countries_data.txt")  #reading the file
countries_data<-subset(countries_data,continent!='Oceania') # taking oceania out
countries_data<-subset(countries_data,year==1997 | year ==2002 | year==2007)

p <- ggplot(countries_data, aes(x =gdpPercap, y = lifeExp))
p<- p + geom_point() + scale_x_log10()
p<-p + geom_point() + labs(x="GDP Per Capita",y="Life Expectancy")
p<-p + geom_point() +facet_wrap(~ year)

p+geom_point()

p<-p+geom_point(aes(shape = continent))+scale_shape_manual(values =c(0,1,2,3))
p<-p+ggtitle('Life Expectancy vs. GDP by continent, 1997-2007')

p+geom_point()

问题是形状ae出来填充而不是空心 即使你向右看,似乎R正在重新塑造空心形状

enter image description here

有什么建议吗?

1 个答案:

答案 0 :(得分:4)

我认为发生的事情是你首先在没有形状美感的情况下绘制点,所以所有点都是圆圈。然后,您要添加一个形状美学(continent),它会在已填充的圆圈顶部覆盖未填充的标记(使用scale_shape_manual选择),使标记看起来已填满。图例标记未填充,因为没有形状美感的所有对geom_point的调用都不会生成图例。

要解决此问题,如果您将geom_point放在第一个geom_point(aes(shape = continent))语句中,则只需拨打一次geom_point()shape=continentaes()即可。换句话说,您可以按如下方式创建绘图:

p <- ggplot(countries_data, 
            aes(x = gdpPercap, y = lifeExp, shape=contintent)) +
  geom_point() + 
  scale_x_log10() + 
  labs(x="GDP Per Capita",y="Life Expectancy") +
  facet_wrap(~ year) +
  ggtitle('Life Expectancy vs. GDP by continent, 1997-2007')

这是一个内置数据框的示例:

# Filled circles
p1 = ggplot(mtcars, aes(wt, mpg)) +
  geom_point() 

# Unfilled markers plotted over filled circles
p2 = p1 + geom_point(aes(shape = factor(cyl))) +
  scale_shape_manual(values=0:2)

# Only unfilled markers plotted
p3 = ggplot(mtcars, aes(wt, mpg, shape=factor(cyl))) +
  geom_point() +
  scale_shape_manual(values=0:2)

enter image description here

此外,为了将来参考,您只需拨打geom_point一次。多次调用(使用相同的数据和美学)只是一遍又一遍地重复绘制相同的内容。您也不需要在每行之后重新保存绘图对象。您可以将每条线链接在一起。因此,下面的代码......

p <- ggplot(countries_data, aes(x =gdpPercap, y = lifeExp))
p <- p + geom_point() + scale_x_log10()
p <- p + geom_point() + labs(x="GDP Per Capita",y="Life Expectancy")
p <- p + geom_point() + facet_wrap(~ year)

...可以更改为:

p <- ggplot(countries_data, aes(x =gdpPercap, y = lifeExp)) +
  geom_point() + 
  scale_x_log10() + 
  labs(x="GDP Per Capita",y="Life Expectancy") +
  facet_wrap(~ year)