ggstance::geom_barh未翻转坐标轴?技术问题求助
ggstance::geom_barh() Output Hey there! I see exactly why your horizontal bar plot is acting up—let’s break this down and fix it right away.
Why Your Current Code Fails
When you use ggplot2::geom_bar(), it automatically treats the mapped variable (class here) as the x-axis categorical variable, then counts how many times each class appears to build vertical bars along the y-axis.
But ggstance::geom_barh() is the horizontal counterpart, and it expects the categorical variable to be mapped to the y-axis instead of the x-axis. Your current code maps class to the x-axis, which throws off the horizontal bar geometry and leads to that weird output you’re seeing.
The Corrected Code
All you need to do is explicitly map class to the y aesthetic in your aes() call:
ggplot2::ggplot(ggplot2::mpg, ggplot2::aes(y = class)) + ggstance::geom_barh()
Quick Breakdown
This tells geom_barh() to use class as the categorical variable along the y-axis, then calculate and display the count of each class on the horizontal x-axis. It’s essentially the same logic as geom_bar(), just swapped to horizontal orientation—perfect for when you need to fit longer category names or prefer a horizontal layout.
内容的提问来源于stack exchange,提问作者balin

