plot_data <- rbind(
data.frame(year = seq(2018,2027), value = seq(1000,10000,1000), type = 'Type A'),
data.frame(year = seq(2018,2027), value = seq(500,5000,500), type = 'Type B')
)
plot_labels <- data.frame(year = seq(2018,2027), label = seq(1500,15000,1500))
ggplot(plot_data, aes(x=as.character(year), y=value, fill=type)) +
geom_bar(width = .6, stat='identity') +
# geom_text(data = plot_labels, aes(x = year, y = text, label = label)) +
scale_x_discrete(name = '') +
scale_y_continuous(name = 'My Label\n') +
scale_fill_manual(name = '', values = c('red', 'blue')) +
theme(
plot.title = element_text(size = 10, hjust = .5),
panel.grid.major = element_line(colour = 'white', size = 1),
panel.grid.minor = element_line(colour = 'white'),
plot.background = element_rect(fill = 'white'),
panel.background = element_rect(fill = 'white'),
axis.text.x = element_text(colour = 'grey20', size = 7, angle = 45, hjust = 1),
axis.title.y = element_text(color = 'grey20', size = 9),
axis.text.y = element_text(colour = 'grey20', size = 7),
legend.position='bottom',
legend.key.size=unit(5,'mm'),
legend.text = element_text(size = 7))
This code will produce a stacked bar chart.
My goal is to label this plot with plot_labels$label
on the same y axis and scale as the stacked bar.
Uncommenting out line beginning with geom_text
in plot definition throws the following error:
Error in eval(expr, envir, enclos) : object 'type' not found
plot_labels$label
values are equivalent to summarizing plot_data$value
by plot_data$year
.
Would much appreciate the help in troubleshooting!
A few problems: 1) the
fill
should be placed ingeom_bar
, otherwise it will be inherited by all geoms that follow. 2) thegeom_col
is better thangeom_bar
when you provide bothx
andy
. 3) ingeom_text
,x
andy
need to be the same type as inggplot
.