如何使用 ggplot 在 r 中绘制多行图
问题描述:
我正在尝试使用 ggplot 在 r 中绘制 3 行图形,但第三行没有出现在图形中.我使用了以下代码:
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)
如果我们检查mdn_idl_pnt
,第三行没有绘制的原因就会很明显.
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
在您的 ggplot
调用中,您映射 x = Year
和 y = Idealpoint
.然而,每个Year
和idealpoint
只有一个值.不能从一个点创建一条线.
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.
也许你想添加一个 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)