我有一個龐大的資料集,這使得圖形繪制變得乏味而復雜。
假設這個簡化的資料集:
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) 它與我的決定為 shape = 21 作斗爭geom_point(),以及 3) 它增加了一個我不想要的巨大傳說。
如何在plotly不添加額外和不需要的美學的情況下個性化互動視窗?
此外,我嘗試使用以下方法洗掉圖例:
guides(fill="none", color="none")
或通過
%>% hide_legend()
但無論哪種方式,都行不通。如何洗掉圖例?
uj5u.com熱心網友回復:
您可以做的是添加label您aes的添加因素,例如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)
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476667.html
上一篇:R中使用ggplot2的精美餅圖
下一篇:使用地圖和散點圖創建多圖
