首页 > 解决方案 > R ggplot scale_fill_gradient2 on histogram vs dotplot

问题描述

我在 ggplot2 中应用scale_fill_gradient2单个变量。 geom_histogram()是我的默认方法,但我想使用geom_dotplot(). 当我加宽 x 轴时,直方图上的填充映射到我的轴限制(这是所需的),但是当使用 dotplot 绘制相同的数据时,填充映射到数据的最小值/最大值,而与 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 命令并产生我想要的填充结果。但是,将“直方图”一词更改为“点图”(仅此而已),填充比例仅与数据的最小值/最大值一致。我想要的是带有直方图填充的点图。

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

具有最小-最大填充比例的点图

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

标签: rggplot2histogram

解决方案


您可以设置limitsin 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))

在此处输入图像描述


推荐阅读