直方图与点图上的 R ggplot scale_fill_gradient2

R ggplot scale_fill_gradient2 on histogram vs dotplot

我在 ggplot2 中对单个变量应用 scale_fill_gradient2geom_histogram() 是我的默认方法,但我想使用 geom_dotplot()。当我加宽我的 x 轴时,直方图上的填充映射到我的轴限制(这是需要的),但是当使用 dotplot 绘制相同的数据时,填充映射到数据的 min/max 而不管 x - 轴限制。示例代码:

### 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)

换句话说,填充比例匹配scale_x_continuous命令并产生我想要的填充结果。但是,将“直方图”一词更改为“点图”(仅此而已),填充比例将完全与数据的 min/max 保持一致。我想要的是带有直方图填充的点图。

### Dot Plot -- fill scales purely with min/max of data
### I want the same shading as in the histogram
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

最终,这里的目标是让点图 fill/scale 与直方图相匹配。谢谢!

您可以在scale_fill_gradient2中设置limits:

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))