简体   繁体   中英

r- ggplot2: polar line plot with 2 lines

Using ggplot2 , I am trying to graph two treatments in a polar line graph. I'm able to graph the points for both treatments and get a line for the first treatment that I input, but the line that I want to connect the second subset is just overlaying over the second.

  category highest lowest
  1        A      71     23
  2        B      81     38
  3        C      77     22
  4        D      83     56
  5        E      84     32
  6        F      82     55
  7        G      73     26

So far, my code looks like this

p1<-ggplot(data=d,aes(x=factor(category),y=highest,group=1)) + 
ylim(0,NA) +
geom_point(color='purple',stat='identity')+
geom_polygon(color='purple',fill=NA)+
coord_polar(start =-pi* 1/7)

p1

p1 + 
geom_point(aes(x=factor(category),y=lowest),color='green',stat='identity')+
geom_polygon(color='green',fill=NA)+
coord_polar(start =-pi* 1/7)

and its looking like this

plot

Any help? Thanks!!

You are still using the overall y aesthetic ("highest") in the second geom_polygon call. To plot a different column, you'll need to define it in aes within the layer.

geom_polygon(aes(y = lowest), color='green',fill=NA)

The more standard way to do such a plot, though, is to get your dataset into a long format, where you grouping variable (highest and lowest) is a variable and all your y values are in a single column for plotting.

library(reshape2)
d2 = melt(d, id.var = "category")

Once you have that you can map color to the grouping variable. You set colors to specific values using scale_color_manual . You get a legend by default (which might be a good thing), but you an suppress it using guide = "none" .

ggplot(data=d2, aes(x=factor(category), y=value, group = variable, color = variable)) + 
    ylim(0,NA) +
    geom_point(, stat='identity') +
    geom_polygon(fill=NA)+
    coord_polar(start =-pi* 1/7) +
    scale_color_manual(values = c("purple", "green"), guide = "none")

Both approaches give the same plot in the end: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM