gpt4 book ai didi

r - 在ggvis图表下方添加水平离散图例

转载 作者:行者123 更新时间:2023-12-04 01:15:02 24 4
gpt4 key购买 nike

我想在 ggvis 下面做一个水平图例图表。我可以使用图例属性将其放置在图表下方,但不知道如何将标签水平放置在图例标题下方。下面是最小的可重现代码(从网上抓取)。

df1 = data.frame(x=sample(1:10), y=sample(1:10))
df2 = data.frame(x=1:10, y=1:10)
df3 = data.frame(x=1:10, y=sqrt(1:10))

df2$id <- 1
df3$id <- 2
df4 <- rbind(df2,df3)
df4$id <- factor(df4$id)

df4 %>% ggvis(x=~x, y=~y, stroke=~id) %>% layer_lines() %>%
# make sure you use add relative scales
add_relative_scales() %>%
# values for x and y need to be between 0 and 1
# e.g for the x-axis 0 is the at far-most left point and 1 at the far-right
add_legend("stroke", title="Cylinders",
properties=legend_props(
legend=list(
x=scaled_value("x_rel", 0.2),
y=scaled_value("y_rel", -.2)
))) %>%
layer_points(x=~x, y=~y, data=df1, stroke:='black')

最佳答案

这肯定是一个黑客,但效果很好:

df4 %>% ggvis(x=~x,y=~y,stroke=~id) %>% layer_lines() %>%
#make sure you use add relative scales
add_relative_scales() %>%
#values for x and y need to be between 0 and 1
#e.g for the x-axis 0 is the at far-most left point and 1 at the far-right
add_legend("stroke", title = "Cylinders", values = c(1, 1),
properties = legend_props(
legend = list(
x = scaled_value("x_rel", 0.2),
y = scaled_value("y_rel", -.2)
))) %>%
add_legend("stroke", title = " ", values = c(2, 2),
properties = legend_props(
legend = list(
x = scaled_value("x_rel", 0.23),
y = scaled_value("y_rel", -.2)
))) %>%
layer_points(x=~x,y=~y,data = df1,stroke:='black')

enter image description here

基本上,我正在添加另一个 add_legend ,设置标题为空,调整 scale_value因此它非常接近第一个图例但不重叠。然后我用 values = c(1,1) 设置第一个图例第二个是 values = c(2,2)以便两个值堆叠在一起。这使它看起来像一个具有水平值的图例。

关于r - 在ggvis图表下方添加水平离散图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37465292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com