valeranth valeranth - 1 year ago 85
R Question

Q: R ggplot2 - Different precision on seperate tick marks

I have been working on creating a histogram of some data I that I have recent generated and in a effort to make the data more readable would like to include the confidence intervals, including having the intervals numerically marked on the tick line.

This has created a small problem with the readability. Using the code below you can see that having mean as a float value will cause all of the tick marks to have the same precision as the mean value leading to a large number of trailing 0's, in this case there are 7 but if you manully set the mean value to something like 3.5 all will have 1 trailing 0.

I was wondering if anyone knows how to set the percision of each mark manually. Ideally I would like to have the marks at 0,1,2,..,10 to be integer while the mean value would have 2 digits of precision shown since I will have a more accurate number listed.


df <- data.frame(x=rexp(1000))

mean = mean(df$x)

ggplot(df, aes(x=x)) +
geom_histogram(binwidth = .05, position="dodge", color="black", fill="transparent") +
geom_vline(data=df, aes(xintercept=mean), linetype="dashed", color="red") +
theme_bw() +
scale_x_continuous(name="Values", expand = c(0, 0), breaks = sort(c(seq(0,10,1), mean)))

Image of the resultant graph from the code above.

Answer Source

You can set the labels parameter of scale_x_continuous. The values still overlap, so adjust accordingly or put the label elsewhere, e.g. with geom_text.

ggplot(df, aes(x = x)) + 
    geom_histogram(binwidth = .05, position = "dodge", color = "black", fill = "transparent") + 
    geom_vline(aes(xintercept = mean), linetype = "dashed", color = "red") +
    theme_bw() +
    scale_x_continuous(name="Values", expand = c(0, 0),
                       breaks = sort(c(seq(0,10,1), mean)), 
                       labels = sort(c(0L:10L, round(mean, digits = 2))))

plot with fixed labels

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download