我正在使用R并使用ggplot制作图表。但是,我试图通过下面的代码徒然将图例添加到我的barplot中。
library(ggplot2)
library(dplyr)
data<- data.frame(years = c(2009:2018),
values <- c(-9400, -8792, -10914, -17996, -25543, -27814, -33335, -38872, -38243, -37034))
my_barplot <- data %>%
ggplot(aes(x=years, y=values))+
xlab('name x axis') + ylab('name y axis') +
geom_col(aes(fill="bla bla"))+
scale_x_continuous(breaks = seq(2009, 2018, by = 2))+
labs(title="title",
subtitle="Subtitle",
caption="Source")+
geom_text(aes(label=paste0((values))),
position=position_stack(vjust=0.5),size=3)+
# scale_color_manual('', labels = 'label', values = 'red') +
stat_smooth(color = "#FC4E07", fill = "#FC4E07",
method = "loess",formula = y ~ x, size = 1, se= FALSE)+
scale_colour_manual(name = 'Legend',
guide = 'legend',
values = c('MA50' = 'blue',
'MA200' = 'red'),
labels = c('SMA(50)',
'SMA(200)'))+
theme_minimal()
您能帮我吗?
答案 0 :(得分:2)
尝试一下。顺便说一句,我还删除了一些不必要的代码:
library(ggplot2)
library(dplyr)
data<- data.frame(years = c(2009:2018),
values <- c(-9400, -8792, -10914, -17996, -25543, -27814, -33335, -38872, -38243, -37034))
my_barplot <- data %>%
ggplot(aes(x=years, y=values))+
xlab('name x axis') + ylab('name y axis') +
geom_col(aes(fill="label_bar"))+
scale_x_continuous(breaks = seq(2009, 2018, by = 2))+
labs(title="title",
subtitle="Subtitle",
caption="Source")+
geom_text(aes(label=paste0((values))),
position=position_stack(vjust=0.5),size=3)+
# scale_color_manual('', labels = 'label', values = 'red') +
stat_smooth(aes(color = "label_loess"),
method = "loess",formula = y ~ x, size = 1, se= FALSE) +
scale_fill_manual(values = c('label_bar' = 'steelblue')) +
scale_colour_manual(values = c('label_loess' = 'red',
'SMA(50)' = 'blue',
'SMA(200)' = 'red'))+
theme_minimal()
my_barplot
由reprex package(v0.3.0)于2020-03-23创建