簡體   English   中英

ggplot中的自定義交互Plotly - R

[英]Custom interaction Plotly in ggplot - R

我有一個龐大的數據集,這使得圖形繪制變得乏味而復雜。

假設這個簡化的數據集:

library(data.table)
library(plotly)
library(ggplot2)
library(dplyr)

df <- data.table(continent = c(rep("America",3), rep("Europe",4)),
           state = c("USA", "Brazil", "Chile", "Italy", "Swiss", "Spain", "Greece"),
           X = rnorm(7, 5, 1),
           Y = rnorm(7, -13, 1),
)

df$X_sd = sd(df$X)
df$Y_sd = sd(df$Y)

考慮為“狀態”設置 > 30 個級別,這使得用不同的顏色或形狀顯示它們變得非常困難。

我決定使用plotly來顯示這個數據集。

這是我所做的:

p <- df %>%
  ggplot(aes(x=X,
              y=Y, 
              fill = continent,
              color = continent)) +
  geom_errorbarh(aes(xmin = X - X_sd,
                     xmax = X + X_sd),
                 size = 0.5,
                 alpha = 0.3) +
  geom_errorbar(aes(ymin = Y - Y_sd,
                    ymax = Y + Y_sd),
                size = 0.5,
                alpha = 0.3) +
  geom_point(shape=21,
    color="black",
    size=3) +
  theme_bw()

ggplotly(p)

但是,交互式窗口不顯示有關國家/地區的信息,這是我想要實現的。 事實上,每次我經過一個點時,我都希望有一個窗口顯示:大陸、國家、X 和 Y(如果我有更多的因素或列,我也想包括它們) .

我試圖在美學中添加shape = country ,但是 1)沒有足夠的形狀,2)它與我決定為geom_point()設置 shape = 21 的決定作斗爭,以及 3)它增加了一個我不知道的巨大傳說不想要。

如何在不添加額外和不需要的美學的情況下個性化plotly的交互窗口?

此外,我嘗試使用以下方法刪除圖例:

guides(fill="none", color="none")+

或通過

%>%  hide_legend()

但無論哪種方式,都行不通。 如何刪除圖例?

您可以做的是在您的aes中添加label以添加諸如state之類的因素。 您可以多次這樣做。 您可以使用以下代碼:

p <- df %>%
  ggplot(aes(label = state,
             x=X,
             y=Y, 
             fill = continent)) +
  geom_errorbarh(aes(xmin = X - X_sd,
                     xmax = X + X_sd),
                 size = 0.5,
                 alpha = 0.3) +
  geom_errorbar(aes(ymin = Y - Y_sd,
                    ymax = Y + Y_sd),
                size = 0.5,
                alpha = 0.3) +
  geom_point(shape=21,
             color="black",
             size=3) +
  theme_bw() +
  theme(legend.position = "none")

ggplotly(p)

輸出:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM