For layouting reasons I would like to position the histgram bars centered on the labels, such that the middle of a bar is on top of the label.
library(ggplot2)
df <- data.frame(x = c(0,0,1,2,2,2))
ggplot(df,aes(x)) +
geom_histogram(binwidth=1) +
scale_x_continuous(breaks=0:2)
This is what it looks so far - the left side of a bar is on top of the label:
Is it possible to adjust the given snippet in such a way? (without using geom_bar instead f.x.)
To place the labels at the center in a histogram plot, we can calculate the mid-point of each patch and place the ticklabels accordinly using xticks() method.
To give labels use set_xlabel() and set_ylabel() functions. We add label to each bar in histogram and for that, we loop over each bar and use text() function to add text over it. We also calculate height and width of each bar so that our label don't coincide with each other.
A label such as age is appropriate for a histogram displaying income levels by age group. Hours is a good label for a histogram displaying hours a group of students spends watching television. Add details along the x and y-axis to indicate quantity and to break the data into equal ranges.
In Matplotlib, we use the hist() function to create histograms. The hist() function will use an array of numbers to create a histogram, the array is sent into the function as an argument.
This doesn't require a categorical x axis, but you'll want to play a little if you have different bin widths than 1.
library(ggplot2)
df <- data.frame(x = c(0,0,1,2,2,2))
ggplot(df,aes(x)) +
geom_histogram(binwidth=1,boundary=-0.5) +
scale_x_continuous(breaks=0:2)
For older ggplot2
(<2.1.0), use geom_histogram(binwidth=1, origin=-0.5)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With