[英]Plotly in R: Piechart subplot changing domains when linked to choropleth with crosstalk
[英]R Plotly linked subplot with percentage histogram and categories coloured
我在 R 中使用 plotly API 创建两个链接图。 第一个是散点图,第二个是条形图,应显示当前选择中属于每个类别的数据百分比。 我无法使百分比按预期运行。
绘图正确呈现,交互式选择工作正常。 当我在顶部散点图中选择一组数据点时,我希望看到属于每个类别的选择的百分比。 相反,我看到的是该类别中该选项中属于该类别的分数的百分比,换句话说,始终为 100%。 我想这是因为我设置了color = ~c
,它将分组应用于类别。
这是一个可重现的示例。 首先创建一些虚拟数据。
library(plotly)
n = 1000
make_axis = function(n) c(rnorm(n, -1, 1), rnorm(n, 2, 0.25))
data = data.frame(
x = make_axis(n),
y = make_axis(n),
c = rep(c("A", "B"), each = n)
)
创建一个sharedData
对象并将其提供给plot_ly()
以作为基础图。
shared_data = data %>%
highlight_key()
baseplot = plot_ly(shared_data)
制作单独的面板。
points = baseplot %>%
add_markers(x = ~x, y = ~y, color = ~c)
bars = baseplot %>%
add_histogram(x = ~c, color = ~c, histnorm = "percent", showlegend = FALSE) %>%
layout(barmode = "group")
并将它们放在一个带有选择和突出显示的链接子图中。
subplot(points, bars) %>%
layout(dragmode = "select") %>%
highlight("plotly_selected")
顺便说一句,当我在add_histogram()
设置histnorm = ""
然后我更接近预期的行为,但我确实想要百分比而不是计数。 当我删除color = ~c
我会更接近预期的行为,但我确实想要一致的配色方案。
我尝试手动提供颜色,但随后一些链接选择中断。 我曾尝试sharedData
对象创建一个单独的汇总数据集,然后对其进行绘制,但这再次打破了图之间的联系。
如果有人对如何解决这个问题有任何线索,我将不胜感激。
对我来说,您正在寻找的行为似乎并没有在情节中实现。
请参阅schema()
: object ► traces ► histogram ► attributes ► histnorm ► description
但是,这是我能够通过add_bars
和处理数据获得的最接近的结果(抱歉添加data.table
,您将能够在基础 R 中执行相同的操作,只是个人喜好):
library(plotly)
library(data.table)
n = 1000
make_axis = function(n) c(rnorm(n, -1, 1), rnorm(n, 2, 0.25))
DT = data.table(
x = make_axis(n),
y = make_axis(n),
c = rep(c("A", "B"), each = n)
)
DT[, grp_percent := rep(100/.N, .N), by = "c"]
shared_data = DT %>%
highlight_key()
baseplot = plot_ly(shared_data)
# Make the individual panels.
points = baseplot %>%
add_markers(x = ~x, y = ~y, color = ~c)
bars = baseplot %>%
add_bars(x = ~c, y = ~grp_percent, color = ~c, showlegend = FALSE) %>%
layout(barmode = "group")
subplot(points, bars) %>%
layout(dragmode = "select") %>%
highlight("plotly_selected")
不幸的是,由此产生的hoverinfo 并不是真正可取的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.