graph percentage in r

To graph percentages in R, you can use the ggplot2 package to create bar plots with the percentage labels.

Here is an example code:

main.r
library(ggplot2)

# create a sample dataset
df <- data.frame(category = c("Category 1", "Category 2", "Category 3"), 
                 count = c(20, 40, 60))

# calculate the percentage for each category
df$percentage <- df$count / sum(df$count) * 100

# create a bar plot with percentage labels
ggplot(df, aes(x = category, y = percentage)) +
  geom_bar(stat = "identity", fill = "blue") +
  geom_text(aes(label = paste0(percentage, "%")), vjust = -0.5) +
  labs(x = "", y = "Percentage") +
  theme_minimal()
510 chars
16 lines

In this example, we first create a sample dataset with three categories and corresponding counts. Then, we calculate the percentage for each category by dividing the count by the total count and multiplying by 100. We then use ggplot() to create a bar plot with category on the x-axis and percentage on the y-axis. We use geom_bar() to create the bars and geom_text() to add the percentage labels on top of each bar. Finally, we use labs() to add the axis labels and theme_minimal() to remove any unnecessary elements.

gistlibby LogSnag