I'm creating a bar plot to display the number of survey responses from each county, and I want to group the responses by county and region. My data looks like this:
head(df)
# A tibble: 6 x 4
responseid region county industry
<dbl> <fct> <fct> <chr>
1 137 West Coast Los Angeles Construction
2 138 West Coast San Diego Energy
3 139 West Coast Orange Professional Services
4 140 East Coast Queens Restaurants
5 144 West Coast San Diego Energy
6 145 East Coast Miami-Dade Public Sector
I'm running this code:
ggplot(df, mapping = aes(x = fct_rev(fct_infreq(county)), y = stat(count))) +
geom_bar(aes(fill = region)) +
coord_flip()+
scale_y_continuous() +
ggtitle("Responses by County") +
ylab("Number of Responses")+
xlab("County") +
labs(fill = "Region") +
geom_text(stat='count', aes(label=..count..), vjust = .5, hjust = -1)
The plot is ordered by response frequency by county. I'd like to make it ordered first by region, then by response count. I want this same chart, but with all the West Coast counties in order from most to least responses, then the East Coast counties in order from most to least responses.
Faceting it doesn't give the effect I want, since it pulls the West Coast responses to a separate grid and you can't compare all the counties by the same y-axis anymore; faceting without the axis flip makes the county names overlap and become illegible.
I also tried to add an interaction argument like this but that didn't change the plot at all:
ggplot(df, mapping = aes(x = fct_rev(fct_infreq(county)), y = stat(count), group = interaction(region, county))) +
geom_bar(aes(fill = region)) +
coord_flip()+
scale_y_continuous() +
ggtitle("Responses by County") +
ylab("Number of Responses")+
xlab("County") +
labs(fill = "Region") +
geom_text(stat='count', aes(label=..count..), vjust = .5, hjust = -1)
Edit: This is what it looks like with facet wrap. I'm not a fan because it's harder to visually compare the bars when they don't start from the same y-axis:
If you remove the coord_flip, all the bars start from the same place, but then you can't read the county names at all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.