Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot:仅为单个变量手动指定颜色_R_Ggplot2 - Fatal编程技术网

R ggplot:仅为单个变量手动指定颜色

R ggplot:仅为单个变量手动指定颜色,r,ggplot2,R,Ggplot2,我有这样一个情节: ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() + xlab('Year') + ylab('GDP per capita') labs(title = "Annual GDP Growth rate (%)") + theme_bw() 现在我只想为一个变量(仅针对一个国家)更改颜色和线条厚度(黑色,比其他颜色厚约30%) 我已经找到了如何为所有变量手动分

我有这样一个情节:

ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() + 
  xlab('Year') + ylab('GDP per capita')
  labs(title = "Annual GDP Growth rate (%)") +
  theme_bw()

现在我只想为一个变量(仅针对一个国家)更改颜色和线条厚度(黑色,比其他颜色厚约30%)


我已经找到了如何为所有变量手动分配颜色,而不是如何只为一个变量分配颜色。此外,根据输入数据,图表可以有不同数量的变量(国家)。

如果没有一些可复制的数据,这有点困难,但您应该能够通过添加一个仅使用特定国家数据的
geom_line()
来实现这一点:

ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() + 
  xlab('Year') + ylab('GDP per capita') +
labs(title = "Annual GDP Growth rate (%)") +
  theme_bw() +
  geom_line(data=subset(data3, country == "China"), colour="black", size=1.5)
让图例与颜色和大小保持一致有点棘手-您可以通过使用
override.aes
手动破解图例来做到这一点,但这不一定是最优雅的解决方案:

# Needed to access hue_pal(), which is where ggplot's
# default colours come from
library(scales)

ggplot(data3, aes(year, NY.GDP.MKTP.KD.ZG, color = country)) + geom_line() + 
  xlab('Year') + ylab('GDP per capita') +
  labs(title = "Annual GDP Growth rate (%)") +
  theme_bw() +
  geom_line(data=subset(data3, country == "World"), colour="black", size=1.5) +
  guides(colour=guide_legend(override.aes=list(
    colour=c(hue_pal()(11)[1:10], "black"), size=c(rep(1, 10), 1.5))))

图片提示:您可以将其添加为链接,具有更高声誉的人可以在之后添加!谢谢,如果你是那个投票支持我的问题的人,我想你给了我足够的声誉来发布图片。嗨,当我这么做的时候,我只得到了一个变量(图中的一行),其他什么都没有。我已经添加了我的全部代码以实现可复制性(数据来自WDI库,因此无需生成它)@user1754606:问题可能只是缺少一个
+
,在
ylab()
之后,我注意到一旦我有了你的代码。哦,我刚刚注意到,当曲线图中的线条变为黑色时,图例中的标签仍然是以前的颜色。如何将图例也更改为黑色?@user1754606:请参阅我的编辑。你可以做到,但不一定漂亮。