本文介绍了使用scale_y_log10使用geom_histogram时如何抑制零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我尝试使用ggplot,geom_histogram和scale_y_log10绘制一个具有log y比例的直方图。大多数区域(计数大于1的区域)看起来是正确的:背景是透明的,直方图条带用黑色默认颜色填充。但在计数为1时,颜色被倒置:黑色背景和直方图条的透明填充。这个代码(下面)在图中产生了这个例子。 任何人都可以解释这个原因吗?我了解log scale出现的问题,但似乎无法找到解决方案。 set.seed(1) df我想要一个简单的解决方法,或者我忽略了一些东西。 < - data.frame(E = sample(runif(100),20,TRUE)) ggplot(df,aes(E))+ geom_histogram(binwidth = 0.1)+ scale_y_log10(limits = c(0.1, 100))+ xlim(0,1) 解决方案您可以将 drop = TRUE 添加到 geom_histogram 调用中,以使用零计数删除分档(请参阅 set.seed(1) df< - data.frame(E = sample(runif(100),20,TRUE)) ggplot(df,aes(E))+ geom_histogram(binwidth = 0.1,drop = TRUE)+ scale_y_log10(limits = c(0.1,100))+ xlim(0,1) 编辑:由于比例从1开始,因此不可能显示高度为1的条。如这个答案,你可以选择从不同层面开始,但可能会产生误导。这里是这个代码: pre $ require(比例) mylog_trans< - 函数(base = x(b)= exp(1),从= 0) { trans inv trans_new(mylog,trans,inv,log_breaks(base = base),domain = c(base ^ from,Inf))} ggplot (df,aes(E))+ geom_histogram(binwidth = 0.1,drop = TRUE)+ scale_y_continuous(trans = mylog_trans(base = 10,from = -1),limits = c(0.1, 100))+ xlim(0,1) I'm trying to plot a histogram with a log y scale using ggplot, geom_histogram and scale_y_log10. Most regions (those with counts greater than 1) appear correct: the background is transparent and the histogram bars are filled with the default color black. But at counts of 1, the colors are inverted: black background and transparent fill of the histogram bars. This code (below) generates the example in the graph.Can anyone explain the cause of this? I understand the problems that come with log scales but I can't seem to find a solution to this. I'm hoping there's a easy fix, or that I overlooked something.set.seed(1)df <- data.frame(E=sample(runif(100), 20, TRUE))ggplot(df,aes(E)) + geom_histogram(binwidth=0.1) + scale_y_log10(limits=c(0.1,100)) + xlim(0,1) 解决方案 You can add drop=TRUE to the geom_histogram call to drop bins with zero counts (see ?stat_bin for details):set.seed(1)df <- data.frame(E=sample(runif(100), 20, TRUE))ggplot(df,aes(E)) + geom_histogram(binwidth=0.1, drop=TRUE) + scale_y_log10(limits=c(0.1,100)) + xlim(0,1)EDIT: Since the scale starts at 1, it is impossible to display a bar of height 1. As mentioned in this answer, you can choose to start at different levels, but it may become misleading. Here's the code for this anyway: require(scales)mylog_trans <-function (base = exp(1), from = 0){ trans <- function(x) log(x, base) - from inv <- function(x) base^(x + from) trans_new("mylog", trans, inv, log_breaks(base = base), domain = c(base^from, Inf))}ggplot(df,aes(E)) + geom_histogram(binwidth=0.1, drop=TRUE) + scale_y_continuous(trans = mylog_trans(base=10, from=-1), limits=c(0.1,100)) + xlim(0,1) 这篇关于使用scale_y_log10使用geom_histogram时如何抑制零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 20:39