使用ggplot2中的scale_fill_brewer()函数为数据设置断点
我正在创建一个地图(等值线),如 ggplot2 wiki 上所述。一切都很顺利,除了我遇到了通过scale_fill_brewer()函数将连续值映射到多边形填充颜色的问题。
这个问题描述了我遇到的问题。正如在答案中一样,我的解决方法是使用 gtools quantcut() 函数将数据预先剪切到容器中:
更新:第一个示例实际上是执行此操作的正确方法
require(gtools) # needed for quantcut()
...
fill_factor <- quantcut(fill_continuous, q=seq(0,1,by=0.25))
ggplot(mydata) +
aes(long,lat,group=group,fill=fill_factor) +
geom_polygon() +
scale_fill_brewer(name="mybins", palette="PuOr")
但是,这是可行的,我觉得我应该能够跳过预先剪切数据的步骤,并使用中断选项执行类似的操作:
ggplot(mydata) +
aes(long,lat,group=group,fill=fill_continuous) +
geom_polygon() +
scale_fill_brewer(names="mybins", palette="PuOr", breaks=quantile(fill_continuous))
但这不起作用。相反,我收到类似以下的错误:
提供给离散scale_brewer的连续变量(综合分数)。
我是否误解了“breaks”选项的目的?或者休息被打破了?
I am creating a map (choropleth) as described on the ggplot2 wiki. Everything works like a charm, except that I am running into an issue mapping a continuous value to the polygon fill color via the scale_fill_brewer() function.
This question describes the problem I'm having. As in the answer, my workaround has been to pre-cut my data into bins using the gtools quantcut() function:
UPDATE: This first example is actually the right way to do this
require(gtools) # needed for quantcut()
...
fill_factor <- quantcut(fill_continuous, q=seq(0,1,by=0.25))
ggplot(mydata) +
aes(long,lat,group=group,fill=fill_factor) +
geom_polygon() +
scale_fill_brewer(name="mybins", palette="PuOr")
This works, however, I feel like I should be able to skip the step of pre-cutting my data and do something like this with the breaks option:
ggplot(mydata) +
aes(long,lat,group=group,fill=fill_continuous) +
geom_polygon() +
scale_fill_brewer(names="mybins", palette="PuOr", breaks=quantile(fill_continuous))
But this doesn't work. Instead I get an error something like:
Continuous variable (composite score) supplied to discrete scale_brewer.
Have I misunderstood the purpose of the "breaks" option? Or is breaks broken?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Hadley 所解释的,中断选项会移动刻度,但不会使数据连续。因此,按照问题中的第一个示例预先切割数据是使用scale_fill_brewer命令的正确方法。
As Hadley explains, the breaks option moves the ticks, but does not make the data continuous. Therefore pre-cutting the data as per the first example in the question is the right way to use the scale_fill_brewer command.
预切割连续数据的一个主要问题是,代码中的不同点使用了三部分信息:
真正的恶性循环。这可以通过提供一个接受数据和调色板的函数来打破,自动导出断点的数量并返回一个可以添加到 ggplot 对象的对象。大致如下:
像这样使用它:
A major issue with pre-cutting continuous data is that there are three pieces of information used at different points in the code:
A true vicious circle. This can be broken by providing a function that accepts the data and the palette, automatically derives the number of break points and returns an object that can be added to the
ggplot
object. Something along the following lines:Use it like this: