简体   繁体   English

如何使用 ggplot 在 r 中使用多行制作 plot

[英]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.我正在尝试使用 ggplot 在 r 中绘制 3 行图表,但第三行未出现在图表中。 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:让我们按原样考虑您的 plot:

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 ,第三行没有 plot 的原因将变得显而易见。

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 .在您的ggplot通话中,您是 map x = Yeary = idealpoint Yet there is only one value of each Year and idealpoint .然而,每Yearidealpoint点只有一个值。 A line cannot be created from a single point.不能从单个点创建线。

Perhaps you meant to add a geom_hline ?也许您打算添加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) 

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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