简体   繁体   中英

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

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) 

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) 

在此处输入图像描述

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