Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align bars of histogram centered on labels

Tags:

r

ggplot2

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:

enter image description here

Is it possible to adjust the given snippet in such a way? (without using geom_bar instead f.x.)

like image 358
Raffael Avatar asked Nov 14 '13 21:11

Raffael


People also ask

How do you center a label on a histogram?

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.

How do you label a histogram in Python?

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.

What is label in histogram?

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.

How do I make a histogram in Matplotlib?

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.


1 Answers

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).

like image 180
colcarroll Avatar answered Nov 07 '22 03:11

colcarroll