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

在ggplot2中重新排序带百分比的条形图问题求助

Fixing Bar Order in Your ggplot Bar Chart

Hey there! Let's sort out that bar ordering problem you're facing. Right now, your bars are likely showing up in the default order of your IssueNew variable (probably alphabetical or the order they appear in your dataset). Here are two easy ways to reorder them by percentage (which ties directly to count, since percentage is count divided by total):

First, make sure you have the forcats package installed and loaded (it’s part of the tidyverse, so if you have tidyverse set up, you’re good to go). We’ll reorder the IssueNew factor based on category count, in descending order (so largest bars first):

# Load required packages if you haven't already
library(ggplot2)
library(forcats)
library(scales)

ggplot(Issues103, aes(fct_reorder(IssueNew, ..count.., .desc = TRUE))) +
  geom_bar(aes(y = (..count..)/sum(..count..))) +
  geom_text(aes(y = ((..count..)/sum(..count..)), 
                label = scales::percent((..count..)/sum(..count..))),
            stat = "count", vjust = -0.25, size = 3.2) +
  scale_y_continuous(labels = scales::percent) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(title = "Issues Discussed in WIR Speeches: 103rd Congress",
       x = "Issue", y = "Percentage")

The key change here is fct_reorder(IssueNew, ..count.., .desc = TRUE): this tells ggplot to reorder IssueNew categories by their count, from largest to smallest. Remove .desc = TRUE if you want ascending order instead.

Method 2: Use Base R's reorder

If you don’t want to use the forcats package, base R’s reorder() works too. Use -..count.. to sort in descending order (drop the minus sign for ascending):

library(ggplot2)
library(scales)

ggplot(Issues103, aes(reorder(IssueNew, -..count..))) +
  geom_bar(aes(y = (..count..)/sum(..count..))) +
  geom_text(aes(y = ((..count..)/sum(..count..)), 
                label = scales::percent((..count..)/sum(..count..))),
            stat = "count", vjust = -0.25, size = 3.2) +
  scale_y_continuous(labels = scales::percent) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(title = "Issues Discussed in WIR Speeches: 103rd Congress",
       x = "Issue", y = "Percentage")

Custom Order Bonus Tip

If you want bars in a specific custom order (not just based on count), manually set the factor levels of IssueNew before plotting:

Issues103$IssueNew <- factor(Issues103$IssueNew, 
                             levels = c("Your Top Issue", "Second Issue", "Third Issue"))

Then use IssueNew normally in your aes—bars will follow your custom sequence.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:04:53