How to make a plot in r with multiple lines using ggplot

早过忘川 提交于 2021-02-11 13:59:54

问题


I am trying to do a graph in r with 3 lines using ggplot, but the third line does not appear in the graph. I used the following code:

us_idlpnts <- subset(unvoting, CountryName == "United States of America")
rus_idlpnts <- subset(unvoting, CountryName == "Russia")

mdn_idl_pnt <- summarize(unvoting, PctAgreeUS = median(PctAgreeUS, na.rm=T), PctAgreeRUSSIA = median(PctAgreeRUSSIA, na.rm=T), idealpoint = median(idealpoint, na.rm=T), Year = median(Year, na.rm= T))

ggplot(NULL, aes(Year, idealpoint)) + geom_line(data = us_idlpnts, col = "blue") + geom_line(data = rus_idlpnts, col = "red") + geom_line(data = mdn_idl_pnt , col = "green") + ggtitle("Ideal Points of US and Russia") + labs(y = "Ideal Points", x = "Year", color = "legend") + scale_color_manual(values= colors) 

回答1:


Let's consider your plot as is:

library(ggplot2)
library(qss)
data(unvoting)
us_idlpnts <- subset(unvoting, CountryName == "United States of America")
rus_idlpnts <- subset(unvoting, CountryName == "Russia")
mdn_idl_pnt <- summarize(unvoting, PctAgreeUS = median(PctAgreeUS, na.rm=T),
                         PctAgreeRUSSIA = median(PctAgreeRUSSIA, na.rm=T),
                         idealpoint = median(idealpoint, na.rm=T),
                         Year = median(Year, na.rm= T))
ggplot(NULL, aes(Year, idealpoint)) +
  geom_line(data = us_idlpnts, col = "blue") +
  geom_line(data = rus_idlpnts, col = "red") +
  geom_line(data = mdn_idl_pnt , col = "green") +
  ggtitle("Ideal Points of US and Russia") +
  labs(y = "Ideal Points", x = "Year", color = "legend") +
  scale_color_manual(values= colors) 

The reason the third line does not plot will become obvious if we inspect mdn_idl_pnt.

mdn_idl_pnt
#  PctAgreeUS PctAgreeRUSSIA idealpoint Year
#1       0.24      0.6567164 -0.1643651 1987

In your ggplot call, you map x = Year and y = idealpoint. Yet there is only one value of each Year and idealpoint. A line cannot be created from a single point.

Perhaps you meant to add a geom_hline?

ggplot(NULL, aes(Year, idealpoint)) +
  geom_line(data = us_idlpnts, col = "blue") +
  geom_line(data = rus_idlpnts, col = "red") +
  geom_hline(yintercept = mdn_idl_pnt$idealpoint, col = "green") +
  ggtitle("Ideal Points of US and Russia") +
  labs(y = "Ideal Points", x = "Year", color = "legend") +
  scale_color_manual(values= colors) 



来源:https://stackoverflow.com/questions/61763329/how-to-make-a-plot-in-r-with-multiple-lines-using-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!