1

I plot two series from the same dataframe. One of them has negative values.

p_change <- ggplot(dx, aes(fill=Group)) +
  geom_histogram(aes(x=posvalues), binwidth=1) +
  geom_histogram(aes(x=negvalues), binwidth=1) +
  xlim(0, 15) +
  ylim(-25, 25) +
  xlab('Number of tokens') +
  theme(
    legend.position = "right",
    text=element_text(size = 19)
  )
p_change

enter image description here

I would like the second histogram to be plotted on the negative y-axis.

reggie
  • 3,523
  • 14
  • 62
  • 97
  • 6
    Please provide a minimal dataset to help us reproduce your current plot. Hard to understand what you mean by negative values, especially since histogram count frequency of occurence. – Adam Quek Jul 05 '22 at 07:24
  • Group by "sign" and sum, and plot as identity. – zx8754 Jul 05 '22 at 07:25

1 Answers1

1

You can try this one. IMO it makes more sense that the negative values are plotted on the xaxis.

library(tidyverse)

# some data in the long format (recommended format for ggplot)
data <- mtcars %>% 
  mutate(negdisp=-disp) %>% 
  select(contains("disp")) %>% 
  pivot_longer(everything()) 

data
# A tibble: 64 x 2
   name    value
   <chr>   <dbl>
 1 disp      160
 2 negdisp  -160
 3 disp      160
 4 negdisp  -160

  data %>% 
  ggplot(aes(value, fill = name)) + 
   geom_histogram() 

enter image description here

The solution with the yaxis can be done using something like

data %>% 
  ggplot(aes(x = abs(value), fill = name)) + 
  stat_bin(aes(y=ifelse(fill == "negdisp", -..count.., ..count..))) 

enter image description here

Roman
  • 17,008
  • 3
  • 36
  • 49