Ben
Ben

Reputation: 1522

Cannot arrange breaks and labels for bar plot

I want to create a diverging bar plot which is quite simple: At the left side there shall be APD2 and on the right side shall be APD1. Hence, for each x-value the according y-value shall be drawn. But that's the point I'm struggling with. I guess it does not work because the y-axis range is not set up properly. Furthermore, this is probably connected to the fact that I don't get it how to set the breaks and labels. The y-values for APD1 and APD2 do never exceed 7000. Shall the breaks then begin at 0 or at -7000?

This is the current plot:

Plot

And this is the code I understand how it should look like:

library(ggplot2)
library(ggthemes)

ggplot(df, aes(x = depth, y = "Number of photons", fill = APD)) +   # Fill column
  geom_bar(stat = "identity", width = .6)  + 
  scale_y_continuous(breaks = c(-7000, -6000, -5000, -4000, -3000, -2000, -1000, 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000), 
                     labels =  c(7000, 6000, 5000, 4000, 3000, 2000, 1000, 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000) 
                     ) +
  coord_flip()  +
  labs(title="APD ratio") +
  theme_tufte() +
  theme(plot.title = element_text(hjust = .5), 
        axis.ticks = element_blank()) + 
  scale_fill_brewer(palette = "Dark2") 

Here the data:

depth= c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
APD_first= c(5900, 5918, 6166, 6167, 5947, 5668, 5633, 5716, 5533, 5463, 5428, 5415, 5326, 5346, 5695, 5771, 5748)
df1<- data.frame(depth, APD_first)
df1["APD"]<- "APD1"
colnames(df1)[2]<- "Number of photons"

depth= c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
APD_second= c(5616, 5710, 5843, 5767, 5766, 5541, 5467, 5406, 5396, 5307, 5229, 5255, 5156, 5359, 5383, 5710, 5651)
df2<- data.frame(depth, APD_second)
df2["APD"]<- "APD2"
colnames(df2)[2]<- "Number of photons"

df<- rbind(df1, df2)

Upvotes: 1

Views: 61

Answers (1)

Z.Lin
Z.Lin

Reputation: 29085

Are you looking for something like this?

plot

colnames(df)[2] <- "Number.of.photons"
ggplot(df,
       aes(x = depth, y = ifelse(APD == "APD1", Number.of.photons, -Number.of.photons),
           fill = APD)) +
  geom_col() +
  scale_y_continuous(breaks = seq(-7000, 7000, 1000),
                     labels = abs) +
  scale_fill_brewer(palette = "Dark2") +
  coord_flip()

If you absolutely need to reference a column with spaces in its name within ggplot's aesthetic mapping, use backticks: i.e. `Number of photons` rather than "Number of photons". The latter would result in what you saw, because it's interpreted as a string of value 1, rather than a column name. In general, though, you'll have less trouble if you replace the spaces with ".", as this allows you to reference the column name in its unquoted form.

Upvotes: 1

Related Questions