R ggplot-将所有离散x值显示在直方图中的轴上 [英] R ggplot - getting all discrete x values to be displayed on axis in histogram

查看:82
本文介绍了R ggplot-将所有离散x值显示在直方图中的轴上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用数据框 df 和列 col_name 时,我使用以下函数来生成直方图,如下图所示.

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.

如何获取x轴以显示 col_name 中存在的所有离散值的标签?

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

推荐答案

将以下内容添加到您的函数中(仅当 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)

这篇关于R ggplot-将所有离散x值显示在直方图中的轴上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆