r - Expand y scale but limit height of y axis line -
my goal make simple column chart in ggplot2
looks following chart (made in excel):
what i'm finding that, example data such (where 1 percentage value close 100%), options plotting data in ggplot2
leave desired. in particular, haven't found way make following 2 simple things happen together:
1) make y-axis line end @ 100%
and
2) make percentage labels on each bar visible
to address issue, i've tried experimenting different arguments scale_y_continuous()
haven't found way meet both of goals above @ same time. can see in example plots , code below.
my question is: how expand y scale percentage labels on each data point visible, y-axis line ends @ 100%?
library(dplyr) library(ggplot2) library(scales) example_df <- data_frame(label = c("a", "b"), percent = c(0.5, 0.99)) example_plot <- example_df %>% ggplot(aes(x = label, y = percent)) + geom_bar(stat = "identity", fill = "dodgerblue4", width = .6) + geom_text(aes(label = percent(percent)), size = 3, vjust = -0.5) + scale_x_discrete(null, expand = c(0, .5)) + theme_classic()
plot desired y-axis line, non-visible label on bar
here happens when set limit on scale_y_continuous()
c(0,1)
:
example_plot + scale_y_continuous(null, limits = c(0, 1.0), breaks = seq(0, 1, .2), labels = function(x) scales::percent(x), expand = c(0, 0)) + labs(title = "y axis line looks perfect, label on bar off")
plot y-axis line long, visible label on bar
and here happens when set limit on scale_y_continuous()
c(0,1.05)
:
example_plot + scale_y_continuous(null, limits = c(0, 1.05), breaks = seq(0, 1, .2), labels = function(x) scales::percent(x), expand = c(0, 0)) + labs(title = "y axis line long, label on bar visible")
you remove regular axis line , use geom_segment
create new one:
example_df %>% ggplot(aes(x = label, y = percent)) + geom_bar(stat = "identity", fill = "dodgerblue4", width = .6) + geom_text(aes(label = percent(percent)), size = 3, vjust = -0.5) + scale_x_discrete("", expand = c(0, .5)) + scale_y_continuous("", breaks = seq(0, 1, .2), labels = percent, limits=c(0,1.05), expand=c(0,0)) + theme_classic() + theme(axis.line.y=element_blank()) + geom_segment(x=.5025, xend=0.5025, y=0, yend=1.002)
to respond comment: when it's outside plot area, 99% label still being drawn, it's "clipped", meaning plot elements outside plot area masked. so, option, still hacky, less hacky original answer, turn off clipping label appears:
library(grid) p = example_df %>% ggplot(aes(x = label, y = percent)) + geom_bar(stat = "identity", fill = "dodgerblue4", width = .6) + geom_text(aes(label = percent(percent)), size = 3, vjust = -0.5) + scale_x_discrete("", expand = c(0, .5)) + scale_y_continuous("", breaks = seq(0, 1, .2), labels = percent, limits=c(0,1), expand=c(0,0)) + theme_classic() + theme(plot.margin=unit(c(10,0,0,0),'pt')) # turn off clipping pg <- ggplot_gtable(ggplot_build(p)) pg$layout$clip[pg$layout$name=="panel"] <- "off" grid.draw(pg)
Comments
Post a Comment