R 使用变换和颜色映射进行绘图
我一直在尝试使用R 使用变换和颜色映射进行绘图,r,r-plotly,R,R Plotly,我一直在尝试使用plot\ly和转换(最终从下拉菜单中转换为子集数据)以及颜色映射 以下是基于mtcars的可复制示例: 变换不带颜色映射 如果排除颜色映射,则一切正常: library(plotly) library(tidyverse) plot_ly( data = mtcars %>% rownames_to_column("id"), x = ~mpg, y = ~disp, text = ~id, type = "scatter", mode = "m
plot\ly
和转换(最终从下拉菜单中转换为子集数据)以及颜色映射
以下是基于mtcars
的可复制示例:
变换
不带颜色映射
如果排除颜色映射,则一切正常:
library(plotly)
library(tidyverse)
plot_ly(
data = mtcars %>% rownames_to_column("id"),
x = ~mpg, y = ~disp, text = ~id,
type = "scatter", mode = "markers+text",
marker = list(size = 10, opacity = 0.8),
transforms = list(
list(
type = "filter",
target = ~cyl,
operation = "=",
value = sort(unique(mtcars$cyl))[1])))
对数据进行过滤,以查找与排序(唯一(mtcars$cyl))[1]=4
匹配的值。到目前为止还不错
使用颜色映射进行变换
我现在喜欢根据mtcars$carb中化油器的数量对标记进行颜色编码;如果我添加一个颜色映射,我最终会
library(plotly)
library(tidyverse)
plot_ly(
data = mtcars %>% rownames_to_column("id"),
x = ~mpg, y = ~disp, text = ~id, color = ~as.factor(carb),
type = "scatter", mode = "markers+text",
marker = list(size = 10, opacity = 0.8),
transforms = list(
list(
type = "filter",
target = ~cyl,
operation = "=",
value = sort(unique(mtcars$cyl))[1])))
不知何故,transforms
过滤器被忽略,因为绘图显示了来自mtcars
wherecyl!=4
。实际上,我不明白是哪个元素决定在这里显示
有人能提供一些见解吗?非常感谢。它似乎不喜欢
颜色中的因子
与过滤器
结合使用。看起来事情变得混乱不堪,例如,color=~factor(carb,levels=unique(carb))
将为您提供另一个选择和情节
下面使用的是因子
(包括标记中的颜色
)。只指定color=~carb
也可以。我知道这些都没有给你相同的情节/传说
library(plotly)
library(magrittr)
plot_ly(
data = mtcars %>% tibble::rownames_to_column("id"),
x = ~mpg, y = ~disp, text = ~id,
type = "scatter", mode = "markers+text",
marker = list(color = ~as.factor(carb), size = 10, opacity = 0.8),
transforms = list(
list(
type = "filter",
target = ~cyl,
operation = "=",
value = sort(unique(mtcars$cyl))[1])))
编辑
显然,您可以通过根据希望使用的因子对数据进行排序来解决重新洗牌问题。下面的代码在这方面运行良好,尽管我仍然不喜欢图例中的所有级别。尽管如此,希望它能有所帮助:
library(plotly)
library(magrittr)
xx <- mtcars[order(mtcars$carb), ]
plot_ly(
data = xx %>% tibble::rownames_to_column("id"),
x = ~mpg, y = ~disp, text = ~id, color = ~factor(carb),
type = "scatter", mode = "markers+text",
marker = list(size = 10, opacity = 0.8),
transforms = list(
list(
type = "filter",
target = ~xx$cyl,
operation = "=",
value = sort(unique(xx$cyl))[1])))
之后,您的案例就可以了(当然,对于其他案例,您可能需要原始的arrange\u safe
功能,所以这只是为了证明一点)。Hi@FKneip;不是答案,但我可以用一些随机样本数据来确认问题;添加符号时也会发生这种情况。我已经开通了一个网站,非常感谢你的回答。(1) 你的编辑似乎和我想做的一样,但我不得不说,我不明白为什么先对数据排序会影响颜色映射/过滤。你能解释一下为什么会这样吗?(2) 您的第一个答案也会进行正确的筛选,但不会生成图例。我甚至不知道您可以在标记
中指定颜色映射。在中,颜色映射直接添加到绘图中
。你知道什么是“正确”的方法吗?至于1),我相信有一个bug,可以通过预先排序来避免。明天我可能有时间更详细地检查一下。关于2),我还没有读过关于什么时候使用什么方法的书。我天真的直觉是“直接”指定它“只要这足以生产您想要的产品,并在需要时切换到较低级别的规格necessary@FKneip我现在给答案添加了一些详细的解释::assignAnywhere
看起来很有趣。但是传统的assignInNamespace
几乎肯定更安全。RolandASc和@FKneip:我在o向你们两人发出ping(不确定是否在GitHub FKNIP上?)。
library(godmode)
arrange_safe_new <- function(x, y) x
godmode:::assignAnywhere("arrange_safe", arrange_safe_new)