Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Bars between x-axis ticks

Tags:

r

ggplot2

axes

The data I need to visualise contains passenger loads on a train between 4 stations. The data is provided in an ordered fashion, ie. between Station A and V there are 432 passengers on the train, between V and B 543 and so on. In the coding example I have ploted the data with ggplot2.

library(tidyverse)

df <- tribble(~Station, ~Passengers,
              "A", 432,
              "V", 543,
              "B", 435,
              "Q", 0)

df$Station <- factor(df$Station, levels=unique(df$Station))

ggplot(data = df, aes(x = Station, y = Passengers)) + 
  geom_bar(stat = "identity")

enter image description here

The problem: I would like to position the x-axis ticks and Station names between the bars. The goal is to shift the bars 50% to the right.

like image 877
flo Avatar asked Jun 14 '26 12:06

flo


1 Answers

We can use position_nudge to adjust the bars:

ggplot(data = df, aes(x = Station, y = Passengers)) + 
  geom_bar(stat = "identity", position = position_nudge(x = 0.5))

enter image description here

like image 72
Gregor Thomas Avatar answered Jun 17 '26 03:06

Gregor Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!