Reputation: 327
I have a dataframe which consists of different rubrics and pageviews, like in the following example:
categories| pageviews
health | 700000
recipes | 1000000
diet | 500000
Now I plot it with the following code to get a barchart:
p <- ggplot(df, aes(reorder(pagePathLevel1, -pageviews), pageviews))
p + geom_bar(fill = "#00CC33", stat = "identity") +
labs(x="categories", y="pageviews") +
scale_y_continuous(labels=function(x) format(x, big.mark = ".", scientific = FALSE)) +
geom_text(aes(label=pageviews), size=4, vjust = 1.2, color = "darkgreen")
Unfortunately, the scale_y_continuoius function only applies to the axis scale, but not to the values in geom_text. Is it possible to also get the thousand separator in the values displayed in the bars?
Upvotes: 1
Views: 753
Reputation: 1411
You can alter the column underlying your label
aesthetic before drawing the plot, like this:
library(scales)
df <- df %>%
mutate(label.pageviews = gsub("\\,",".", scales::comma(pageviews)))
This essentially uses the comma
function from the scales
package to insert the separators. Since you want dots instead of commas, the gsub
part replaces one with the other.
You then only need to replace the old label
aesthetic with the newly generated column, and then should get something like this:
p + geom_bar(fill = "#00CC33", stat = "identity") +
labs(x="categories", y="pageviews") +
scale_y_continuous(labels=function(x) format(x, big.mark = ".", scientific = FALSE)) +
geom_text(aes(label=label.pageviews), size=4, vjust = 1.2, color = "darkgreen")
Upvotes: 2