How to change the positions of numbers on the x-axis in geom_bar()
How to change the positions of numbers on the x-axis in geom_bar()
First, sorry for my bad english :( .
I have a question to the geom_bar
: In my plot, the numbers are in the middle of a bar. For example, there appears to be nearly 50'0000 trees (Bäume
) with IBaum = 5
, but in realitythere are nearly 50'000 trees BETWEEN 0 and 5.
geom_bar
Bäume
IBaum = 5
So my Question is: How can I change the position of the numbers in the x-axis?
my current code is:
p1 = ggplot(data = plotdat,
aes(x = factor(IB), y = Anzahl, fill = factor(PFT, levels = c(1,2,3,4)))) +
geom_bar(stat = "identity", width = 0.8, position = "stack")+
labs(title = TeX(paste("Anzahl der Bäume mit Wachstum $\geq$ 0 zu $I_Baum$",
sep = "" )),
x = TeX(paste("$I_Baum $", "$\lbrack$%$\rbrack$", "aus Inventur", invn[1],
sep = " ")),
y = TeX("Anzahl der Bäume mit Wachstum $\geq$ 0")) +
scale_fill_manual("PFT",
values = c("#95C11F", "#788938", "#243B0B", "#006633"),
labels= c(1,2,3,4)) +
theme_minimal(base_size = 14)
dput(plotdat)
1 Answer
1
If your x-axis is continuous (rather than discrete), you can position breaks at non-integer positions. Here's a toy dataset for illustration:
data <- mtcars %>% mutate(x = factor(cyl)) %>% count(x)
> data
# A tibble: 3 x 2
x n
<fctr> <int>
1 4 11
2 6 7
3 8 14
The x variable is a factor here (corresponding to x = factor(IB)
in your code). If we plot it as is, the labels would be centered at the middle of each bar. However, if we convert the x variable back to a numeric value, we can specify breaks in the following manner, which inserts a "0" label at the start (x = 0.5), & shifts all other labels rightwards by 0.5:
x = factor(IB)
ggplot(data,
aes(x = as.integer(x), y = n)) +
geom_col() +
scale_x_continuous(breaks = c(0.5, 0.5 + seq_along(levels(data$x))),
labels = c("0", levels(data$x))) +
theme_minimal()
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Welcome to S.O.! To make easier help you, you should provide some data to reproduce your code, similar to yours. This means you can post the result of
dput(plotdat)
if you can share your original data or create some fake data similar to yours and post them.– s_t
Aug 13 at 8:09