Adjusting y axis origin for stacked geom_bar in ggplot2

geotheory

I want to plot stacked bar plot with ggplot2 and am having difficulty getting the colour mapping and stack order right. The following example has been developed from this SO answer to achieve a non-zero y-axis origin, but as you can see it creates other problems. The colours don't map properly and the plot order is wrong. Grateful for any pointers on the best way to handle this. The desired output should scale colours as per the factor levels for rating, with colours in the order specified.

require(ggplot2)
d = data.frame(grp = rep(c('A','B'), each = 4), 
               rating = rep(c('bad','poor','ok','good'), 2),
               value = c(15,45,35,5,5,15,55,30), stringsAsFactors = F)

if(require(reshape2)) reshape2::dcast(d, grp ~ rating) # show structure

d$rating = ordered(d$rating, levels=c('bad','poor','ok','good'))
d$grp = ordered(d$grp, levels=c('B','A'))

# split datsets so we can plot 'negative' bars
d1 = subset(d, rating %in% c('ok','good'))
d2 = subset(d, rating %in% c('poor','bad'))

ggplot() + 
  geom_bar(data = d1, aes(x=grp, y=value, fill=rating), stat='identity', position='stack') + 
  geom_bar(data = d2, aes(x=grp, y=-value, fill=rating), stat='identity', position='stack') + 
  scale_fill_manual(values=c('red','pink','lightgreen','green')) +
  geom_line(data=d1, aes(x=c(.5,2.5), y=c(0,0)), size=2, linetype='dashed') +
  coord_flip()

enter image description here

Serban Tanasa

Perhaps a bit of reordering and using limits() will help:

d2 <- d2[order(d2$rating, decreasing =T),]

ggplot() + 
     geom_bar(data = d1, aes(x=grp, y=value, fill=rating), stat='identity',
               position='stack') + 
     geom_bar(data = d2, aes(x=grp, y=-value, fill=rating), stat='identity', 
               position='stack') + 
     scale_fill_manual(values=c('red','pink','lightgreen','green'),
                       limits=c("bad","poor","ok","good"))+
     geom_line(data=d1, aes(x=c(.5,2.5), y=c(0,0)), size=2, linetype='dashed') +
     coord_flip()

enter image description here

For anyone who wishes to learn ggplot2, I strongly recommend getting the Winston Chang's R Graphics Cookbook.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

R: ggplot stacked bar chart with counts on y axis but percentage as label

How to start ggplot2 geom_bar from different origin

Adjusting (Stacked) Bar Width according to Proportions of Categories in ggplot2

Show percent of total on top of geom_bar in ggplot2 while showing counts on y axis

ggplot2: geom_bar with custom y limits

R ggplot2 stacked barplot, percent on y axis, counts in bars

Manually change order of y axis items on complicated stacked bar chart in ggplot2

How to get a common legend for stacked geom_bar and geom_point in ggplot2?

scaling x and y axis (geom_bar)

R: Multiple Columns for Each X-axis Element in Stacked geom_bar (ggplot)

ggplot2. How to make geom_bar stacked chart y-range 0-100%?

R ggplot2: labels inside bars, no stacked geom_bar

Label ggplot geom_bar with total stacked bar values

Grouped stacked bar chart in ggplot2 where each stack corresponds to its y axis value

Adjusting Y axis values bar graph

Adjusting the secondary y axis using ggplot

geom_bar ggplot2 stacked, grouped bar plot with positive and negative values - pyramid plot

Rstudio reorder stacked ggplot geom_bar

Stacked bar plot without y-axis values adding together (ggplot2)

Breaking y-axis in ggplot2 with geom_bar

Labelling geom_bar plot at a fixed distance from y-axis in ggplot

Adjusting y axis limits in ggplot2 with facet and "free" scales

ggplot2: Value labels in stacked barplot with geom_bar(position = 'fill')

How to modify the limits of y axis of a stacked bar chart in polar coordinates using ggplot2?

Manually adjusting colors in ggplot (geom_bar)

R ggplot2 geom_bar y-axis sequence similar to respective column values sequence

In ggplot geom_bar, the y axis labels are cluttered at the bottom of bar chart

R & ggplot2: 100% geom_bar + geom_line for average using secondary y axis

Customising X-axis on Stacked Bar Graph GGplot2

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive