简体   繁体   中英

R ggplot - getting all discrete x values to be displayed on axis in histogram

With a data frame df and a column col_name I use the below function to generate histograms like in the figure below.

myHistogramDensity <- function(df, col_name) {
  p1 <- ggplot(df, aes_string(x=col_name)) + 
    geom_histogram(aes(y=..density..), binwidth=1, colour="black", fill="white")
  p1 <- p1 + scale_y_continuous(labels=percent) 
  p1 <- p1 + annotation_custom(tableGrob(myMinMaxMed(df, col_name), rows = NULL),
                               xmin=10, xmax=13, ymin=0.5, ymax=0.6)
  return (p1)
}

This gives me a histogram like below.

How do I get the x-axis to display labels for all discrete values present in col_name ?

直方图

Add the following to your function (this only works if col_name is made up of integer values...since you said "discrete" in your request, I assume this should work)

x_axis_labels <- min(df[,col_name]):max(df[,col_name])

p1 <- p1 + scale_x_continuous(labels = x_axis_labels, breaks = x_axis_labels)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM