簡體   English   中英

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

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

我正在嘗試使用 ggplot 在 r 中繪制 3 行圖表,但第三行未出現在圖表中。 我使用了以下代碼:

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) 

讓我們按原樣考慮您的 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) 

在此處輸入圖像描述

如果我們檢查mdn_idl_pnt ,第三行沒有 plot 的原因將變得顯而易見。

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

在您的ggplot通話中,您是 map x = Yeary = idealpoint 然而,每Yearidealpoint點只有一個值。 不能從單個點創建線。

也許您打算添加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