我遇到一个奇怪的问题,以前似乎也找不到类似问题。
我有数据:
> econ3
# A tibble: 6 x 6
# Groups: decade [6]
decade mean.pce mean.pop mean.uempmed mean.unemploy mean.psavert
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1960 568. 201165. 4.52 2854. 11.2
2 1970 1038. 214969. 6.29 5818. 11.8
3 1980 2620. 237423. 7.2 8308. 9.30
4 1990 4924. 264777. 7.58 7566. 6.71
5 2000 8501. 294869. 9.26 8269. 4.26
6 2010 11143. 314800. 18.2 12186. 5.7
当我使用它绘制图时,一切看起来都很棒:
ggplot(econ3, aes(x=decade, y=mean.uempmed, size=mean.unemploy),guide=FALSE)+
geom_point(colour="blue", fill="lightblue", shape=21)+
scale_size_area(max_size = 15)+
theme_gray()+
labs(title = "Unemployment Level per Decade",
subtitle = "(1967-2015)",
caption = "Data from the US economic time series.",
tag = "Figure 3",
x = "Mean of Median Duration of Unemployment (Weeks)",
y = "Decade")
但是,一旦我使用geom_smooth添加趋势线,图例就会被完全破坏。
ggplot(econ3, aes(x=decade, y=mean.uempmed, size=mean.unemploy),guide=FALSE)+
geom_point(colour="blue", fill="lightblue", shape=21)+
scale_size_area(max_size = 15)+
geom_smooth(method=lm, se=FALSE, formula = y~x, aes(color="lm"))+
theme_gray()+
labs(title = "Unemployment Level per Decade",
subtitle = "(1967-2015)",
caption = "Data from the US economic time series.",
tag = "Figure 3",
x = "Mean of Median Duration of Unemployment (Weeks)",
y = "Decade")
Plot with trendline and broken legend
我不太确定是什么原因引起的或如何解决。我敢肯定它一定很简单。
答案 0 :(得分:2)
我认为这是因为size=mean.unemploy
位于全球。如果将其放在aes
的{{1}}中,它将影响整个ggplot
。这意味着新的geom
也会读取geom_smooth
参数。
由于size
仅需要size
,因此可以将其放在geom_point
的{{1}}中。您可能只更改该部分。
mapping
如果您修改前两行,则点的图例将不会被触及。
答案 1 :(得分:0)
您可以尝试一下。看起来像size
参数与您选择的形状相结合,使整个图例背景成为您选择的颜色。您可以重新排列和更改图例以反映您选择的灰色。唯一的问题是,您会丢失图例中各个点周围的蓝色边框,但是我觉得没有它,您不会丢失任何信息。
library(tidyverse)
df <- read_table2("decade mean.pce mean.pop mean.uempmed mean.unemploy mean.psavert
1960 568. 201165. 4.52 2854. 11.2
1970 1038. 214969. 6.29 5818. 11.8
1980 2620. 237423. 7.2 8308. 9.30
1990 4924. 264777. 7.58 7566. 6.71
2000 8501. 294869. 9.26 8269. 4.26
2010 11143. 314800. 18.2 12186. 5.7")
df %>%
ggplot(aes(x=decade, y=mean.uempmed, size=mean.unemploy))+
geom_smooth(method=lm, se=FALSE, aes(colour = "lm"))+
geom_point(colour="blue", fill="lightblue", shape=21)+
scale_size_area(max_size = 15)+
theme_gray()+
labs(title = "Unemployment Level per Decade",
subtitle = "(1967-2015)",
caption = "Data from the US economic time series.",
tag = "Figure 3",
x = "Mean of Median Duration of Unemployment (Weeks)",
y = "Decade")+
guides(size = guide_legend(override.aes = list(color = "grey90")))