You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ggplot2基于DataFrame绘制带百分比标签的自定义柱状图

Got it, let's walk through building this bar plot exactly as you described using ggplot2. Here's a straightforward, step-by-step solution:

Step 1: Structure Your Data Properly

First, we'll organize your raw values into a data frame that directly maps the original column names to friendly race labels. This avoids having to manually rewrite x-axis labels later:

library(ggplot2)

# Create a data frame with race names and their proportional values
demo_data <- data.frame(
  Race = c("Asian", "Black", "Hispanic", "White", "Other"),
  Proportion = c(0.26554, 0.25454, 0.145454, 0.22454, 0.23123)
)

# Optional: Lock the x-axis order to match your original data (prevents auto-sorting)
demo_data$Race <- factor(demo_data$Race, levels = c("Asian", "Black", "Hispanic", "White", "Other"))

Step 2: Build the Bar Plot with Percentage Formatting

We'll use ggplot2 to draw the bars, then format both the bar labels and axis ticks to show integer percentages (like 27%, 25%):

# Load the scales package for easy percentage formatting (optional but convenient)
library(scales)

ggplot(demo_data, aes(x = Race, y = Proportion)) +
  # Draw the bars
  geom_bar(stat = "identity", fill = "#2c3e50", alpha = 0.8) +
  # Add percentage labels on top of each bar (rounded to whole numbers)
  geom_text(
    aes(label = percent(Proportion, accuracy = 1)),
    vjust = -0.3,  # Move label above the bar
    size = 4,
    color = "#2c3e50"
  ) +
  # Format y-axis ticks as whole-number percentages
  scale_y_continuous(
    labels = percent_format(accuracy = 1),
    limits = c(0, 0.3)  # Expand y-axis to fit labels above bars
  ) +
  # Customize axis titles and plot theme
  labs(
    x = "Racial Group",
    y = "Percentage of Population",
    title = "Demographic Breakdown"
  ) +
  theme_minimal()

Alternative: No Extra Package Needed

If you don't want to use the scales package, you can manually format the percentages with sprintf():

ggplot(demo_data, aes(x = Race, y = Proportion)) +
  geom_bar(stat = "identity", fill = "#2c3e50", alpha = 0.8) +
  geom_text(
    aes(label = sprintf("%d%%", round(Proportion * 100))),
    vjust = -0.3,
    size = 4,
    color = "#2c3e50"
  ) +
  scale_y_continuous(
    labels = function(x) sprintf("%d%%", round(x * 100)),
    limits = c(0, 0.3)
  ) +
  labs(x = "Racial Group", y = "Percentage of Population", title = "Demographic Breakdown") +
  theme_minimal()

What This Does:

  • The x-axis automatically uses the friendly race names we defined in the data frame (no need to manually override labels)
  • Both the bar labels and y-axis ticks show rounded whole-number percentages (27%, 25%, etc.)
  • The theme and formatting keep the plot clean and readable

内容的提问来源于stack exchange,提问作者user35131

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:42:40