I've built a function that utilizes ggplot2 to create a bar chart for a given style of summary table, but there are a few changes I'd like to make that I haven't quite figured out. Here's what the function looks like:
bar_chart_dist <- function(df, x_var, y_var, title) {
title_in_fun <- title
p <- ggplot(df, aes_string(x = df[,x_var], y = df[,y_var])) +
geom_bar(stat = "identity", fill="#005a8c") +
geom_text(aes_string(label= y_var, vjust = -0.2)) +
xlab("") + ylab(y_var) + my_theme() +
ggtitle(title_in_fun) + scale_y_continuous(limits=c(0,100))
return(p)
}
The my_theme
function edits the font family to Open Sans and changes the color to grey, among other things.
The data frames I am using with this function are each three variables long -- topic (this name changes with each given dataframe), n (number of observations) and percent_of_population (pre-calculated percent of total population in a given group). I'm using topic as my x_var
and percent_of_population as my y_var
.
There are a few things here I haven't gotten to work:
1) I'd like the y-axis to be labeled with a percent sign (%) and to span 0% to 100%. I've tried to edit the scale_y_continuous argument
to be:
scale_y_continuous(labels=percent, limits=c(0,100))
but that changes the scale such that my upper boundary is 10,000%.
2) I'd like to change the font color, size, and family in the geom_text argument, as well as add a % sign to the label. The family I'd like to use is Open Sans, but it doesn't seem to recognize that. When I set size = 4
, a legend is created, which does not seem to happen in the examples I've looked at.
Any help you guys can provide is very much appreciated. I'm not sure what's not working because this is wrapped in a function, and what's not working because it's the wrong approach. Here's what the plot looks like in current state: