Adam_S
Adam_S

Reputation: 770

Add comma at thousandths in plot label

I have eg data below:

eg_data_x <- data.frame(
period = c("1", "2", "1 + 2"),
grp = c("1", "2", "1 + 2"),
sum_period = c(20000, 30000, 50000))
eg_data_x$period <- factor(eg_data_x$period, levels = c("1", "2", "1 + 2"))
eg_data_x$grp <- factor(eg_data_x$grp, levels = c("1", "2", "1 + 2"))

I have the syntax below to create a bar graph that totals rubber chickens by period. I have the y axis labeled such that there is a comma for the thousandths place (1,000 vs 1000).

I need to add a comma in the same way to the values in the graph itself: 20000, 30000, and 50000 need to become 20,000, 30,000, and 50,000. I have not found documentation for ggplot2 that explains how to add this to the graph value labels.

How do I add this same comma into the values in the graph themselves?

library(ggplo2)
total_chickens_by_period <-  (
(ggplot(data = eg_data_x, aes(x=period, y=sum_period, fill = grp)) +
 geom_bar(stat = "identity", color = "black")) +
scale_fill_manual(values = c("red", "green", "gold")) +
scale_y_continuous(labels = scales::comma) +
geom_text(aes(label = sum_period), position = position_stack(vjust = 0.9), fontface = "bold") +
ggtitle("Total Rubber Chickens by Period") + xlab("Period") + ylab("Chickens") +
theme(plot.title = element_text(color = "black", size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(color = "black", size = 12, face = "bold"), 
      axis.title.y = element_text(color = "black", size = 12, face = "bold")) +
labs(fill = "Period") )

total_chickens_by_period

Upvotes: 1

Views: 1627

Answers (1)

pogibas
pogibas

Reputation: 28339

You just need to format your numbers (labels) with format using big.mark (you can pass it directly to aes).

library(ggplot2)
# Using OPs data
ggplot(eg_data_x, aes(period, sum_period, fill = grp)) +
    geom_bar(stat = "identity", color = "black") +
    scale_y_continuous(labels = scales::comma) +
    geom_text(aes(label = format(sum_period, big.mark = ",")), 
              position = position_stack(vjust = 0.9))

enter image description here

Upvotes: 4

Related Questions