Reputation: 3
I'm trying to create a figure in r using ggplot2, I use facet_wrap to duplicate 3 sets of stacked bar graphs for different type of setting. However when I use geom_text to only label values that are more than 1.5, I received this error:
Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = c(1L, 1L, 1L, 1L, :
replacement has 24 rows, data has 16
Please advise
Here's my code for the graph:
ggplot(data, aes(x = year, y = percent, fill = facility,label = round(percent))) + geom_bar(aes(y = percent, x = year, fill = facility),
data = data,stat="identity") +
geom_line(aes(x=year, y =percent),linetype="dashed",color="black", position = 'stack',data = data)+
geom_text(data = subset(data,percent>1.5),size = 3, position = position_stack(vjust = 0.5),color="white")+
theme(legend.position="bottom", legend.direction="horizontal",
legend.title = element_blank()) +
scale_y_continuous(labels = dollar_format(suffix = "%", prefix = "")) +
scale_x_continuous(breaks=0:1,
labels=c("2010","2015"))+
labs(x="", y="Percentage") +
ggtitle("Year comparison") +
coord_flip()+
theme(plot.title = element_text(size=20,face="bold",hjust = 0.5))+
facet_wrap(~data$type, ncol = 1, scales = "free")
Here is the image... I'm basically trying to get rid of the label 0 in the picture
Thank you!!!
Upvotes: 0
Views: 368
Reputation: 1831
When you're doing your facet_wrap()
, you're including the full column of "type" (data$type
) from the original dataframe, presumably 24 rows long. You want to use a form like facet_wrap(~ type)
to allow ggplot2
to use the data dynamic to the facet.
A little hard to explain, but maybe easy to play around with in sample data.
Won't work
library(tidyverse)
iris %>%
ggplot(aes(Sepal.Length, Sepal.Width, label = Species)) +
geom_point() +
geom_text(data = subset(iris, Sepal.Length > 6)) +
facet_wrap(~ iris$Species)
#> Error in `$<-.data.frame`(`*tmp*`, "PANEL", value = structure(c(1L, 1L, : replacement has 150 rows, data has 61
Will work
iris %>%
ggplot(aes(Sepal.Length, Sepal.Width, label = Species)) +
geom_point() +
geom_text(data = subset(iris, Sepal.Length > 6)) +
facet_wrap(~ Species)
Upvotes: 1