直方图与点图上的R ggplot scale_fill_gradient2

问题描述

我在ggplot2中将while true: q1 = input('Would like to see data of Washington,Chicago or New York? \n') if q1 not in [ 'Washington','Chicago','New York' ]: print('invalid input,please select a name of a city!') else: break 应用于单个变量。 scale_fill_gradient2是我的方法,但我想使用geom_histogram()。当我加宽x轴时,直方图上的填充会映射到我的轴限制(这是需要的),但是当使用点图绘制相同的数据时,无论x轴如何,填充都会映射到数据的最小值/最大值限制。示例代码

geom_dotplot()

Historgram with properly-scaled fill

换句话说,填充比例匹配scale_x_continuous命令,并生成我想要的填充结果。但是,将单词“ histogram”更改为“ dotplot”(以及其他所有内容),填充比例将完全停留在数据的最小值/最大值之间。我想要的是带有直方图填充的点图。

### Use the Iris Data
df <- iris

### Basic ggplot setup
p <- ggplot(df,aes(x=Sepal.Length)) 


## Histogram -- fill scales with my axis limits (desired)
p + geom_histogram(color="black",aes(fill = ..x..)) +
scale_x_continuous(limits=c(2,10))+
scale_fill_gradient2(
    low = "blue",high = "red",mid = "white",midpoint=6)

Dotplot with min-max fill scale

最终,这里的目标是使点图填充/比例与直方图相匹配。谢谢!

解决方法

您可以在limits中设置scale_fill_gradient2

p + geom_dotplot(color="black",aes(fill = ..x..)) +
scale_x_continuous(limits = c(2,10))+
scale_fill_gradient2(
    low = "blue",high = "red",mid = "white",midpoint = 6,limits = c(2,10))

enter image description here