通过绘制子集,其他组不会包含在右侧的颜色图例中。下面的替代方法操纵因子水平并使用定制的色标来克服这个问题。
准备数据
假设GDP_long
包含长格式的数据。这与 OP 显示的数据一致(GDP_lineplot
,但请参阅下面的数据部分以了解差异)。为了操纵因子水平,forcats
使用包(并且data.table
).
library(data.table)
library(forcats)
# coerce to data.table, reorder factors by values in last = most actual year
setDT(GDP_long)[, Country := fct_reorder(Country, -value, last)]
# create new factor which collapses all countries to "Other" except the top 4 countries
GDP_long[, top_country := fct_other(Country, keep = head(levels(Country), 4))]
创建情节
library(ggplot2)
ggplot(GDP_long, aes(Year, value/1e12, group = Country, colour = top_country)) +
geom_point() + geom_line(size = 1) + theme_bw() + ylab("GDP(USD in Trillions)") +
scale_colour_manual(name = "Country",
values = c("green3", "orange", "blue", "red", "grey"))
该图表现在与预期结果非常相似。前 4 个国家/地区的线条以不同颜色显示,而其他国家/地区以灰色显示,但确实出现在右侧的颜色图例中。
请注意,group
仍然需要美观,以便为每个国家绘制一条线,而colour
是由水平控制的top_country
.
Data
数据集太大,无法在此处复制(即使使用dput()
)。结构
str(GDP_long)
'data.frame': 1763 obs. of 3 variables:
$ Country: chr "Afghanistan" "Albania" "Algeria" "Andorra" ...
$ Year : int 2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...
$ value : num 9.84e+09 1.07e+10 1.35e+11 4.01e+09 6.04e+10 ...
与 OP 的数据类似,但variable
列已转换为整数列year
。这将给出一个格式良好的 x 轴,无需额外的努力。