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

如何在ggplot中翻转堆叠并排条形图(附gene_cancer2_f数据集)

Hey there! Let's figure out how to flip your stacked grouped bar chart in ggplot2 using your gene_cancer2_f dataset. First, I’ll note that your dput output cuts off a bit— I’m assuming there’s a numeric column (like Count or Expression) that represents the height of your bars (since we need a value to map to the y-axis for bar charts).

Step 1: Build your base stacked/grouped bar chart

First, let’s create the vertical version of your stacked bar chart. For example, if you want to stack Cancer categories within each Gene group:

library(ggplot2)

# Vertical stacked bar chart
base_plot <- ggplot(gene_cancer2_f, aes(x = Gene, y = Value, fill = Cancer)) +
  geom_col(position = position_stack()) # Use position_stack() for stacking; position_dodge() for side-by-side groups

Step 2: Flip the chart to horizontal

The easiest way to flip the entire chart (swap x and y axes) is to add coord_flip() to your plot:

# Horizontal stacked bar chart
base_plot + coord_flip()

If you need a stacked "side-by-side" chart

If by "stacked并排" you mean grouped stacked bars (e.g., different groups with stacked bars next to each other), you can adjust the position parameter and still flip it:

# Vertical grouped stacked bars
grouped_stacked <- ggplot(gene_cancer2_f, aes(x = Cancer, y = Value, fill = Gene)) +
  geom_col(position = position_dodge(width = 0.9))

# Flip to horizontal
grouped_stacked + coord_flip()

Quick note

coord_flip() works by swapping the x and y axes entirely—you don’t have to rewrite your entire aes mapping. If you prefer, you could also swap the x and y variables in your aes() call directly, but coord_flip() is more straightforward when you already have a working vertical chart.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:35:09