I want to add custom text to a predefined location into my ggplot.
I've searched at various places and I think I almost got it, but something in my code is not making it work properly.
Here is the sample data:
x <- data.frame(Snapshot_Date = c(
"2016-12-31",
"2016-12-31",
"2016-12-31",
"2016-12-31",
"2017-12-31",
"2017-12-31",
"2017-12-31",
"2017-12-31"),
NewExisting = c('Existing',
'Existing',
'New',
'New',
'Existing',
'Existing',
'New',
'New'
),
Product = c( 'CC',
'ETA',
'CC',
'ETA',
'CC',
'ETA',
'CC',
'ETA'
),
prop = c(0.2384310,
0.4268317,
0.2099592,
0.4991919,
0.2201962,
0.4729444,
0.1375661,
0.5504558)
,stringsAsFactors = F)
x$Snapshot_Date <- as.factor(x$Snapshot_Date)
x$NewExisting <- as.factor(x$NewExisting)
I have created a seperate df
for the corrdinates, as recommended by various sites:
facet_group <- data.frame(NewExisting = c("Existing","New")) # order matters
lable.coord <- data.frame(
x=c(-Inf,-Inf),y = c(Inf,Inf),
facet_group,
labs = c("lab1","label2"),
hjust1 = c(0,0),
vjust1 = c(1,1))
Now when I plot the graph I get an error:Error in FUN(X[[i]], ...) : object 'Snapshot_Date' not found
ggplot(x,aes(x = Product, y = prop, fill = Snapshot_Date)) +
geom_col(position = position_dodge()) +
facet_wrap(~NewExisting, ncol = 1, scales = "free") +
geom_text(aes(label = percent(prop)),
position = position_dodge(width = 0.9),
vjust = -.5,
cex = 4,
colour = "black"
)+ # works upto here
geom_text(data = lable.coord, aes(
x = x, y = y,
label = labs,
group = NULL,
vjust = vjust1,
hjust = hjust1
))
The code appears to work upto just before the second use of geom_text()
. It seems that using a different dataset is causing the problem.
If I adjust the code and move the fill = Snapshot_date
to the geom_col()
instead, then the graphs plots. But now it seems to ignore the position = position_dodge(width = 0.9)
argument.
ggplot(x,aes(x = Product, y = prop)) +
geom_col(aes( fill = Snapshot_Date),position = position_dodge()) +
facet_wrap(~NewExisting, ncol = 1, scales = "free") +
geom_text(aes(label = percent(prop)),
position = position_dodge(width = 0.9),
vjust = -.5,
cex = 4,
colour = "black"
)+
geom_text(data = lable.coord, aes(
x = x, y = y,
label = labs,
group = NULL,
vjust = vjust1,
hjust = hjust1
))
How do I keep the custom text in the corners and get it to show labels over the bars?
Thank you