如何在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

