[英]R Plotly how to remove the grouping on the added linear regression line
我正在嘗試繪制 plot,其中對於散點 plot,顏色代表該區域。 但是我注意到,當我添加一條線性回歸線時,它仍然遵循區域上的顏色編碼(和分組),因此它使這條線變得如此奇怪並且圖例太混亂了。
我想知道是否有辦法添加一條擬合線但忽略該區域,或者有沒有辦法仍然保留圓圈的圖例但刪除線的圖例? 謝謝
我的 plotly 代碼如下所示:
fig1 <- plot_ly(data = df1,
x = ~GDP_per_Capita,
y = ~Top_1000_Uni_per_Pop,
type = "scatter",
mode = "markers",
color = ~Region,
size = ~Top_1000_Uni,
hoverinfo = "text",
text = paste("Country: ", df1$TableName,
"<br>",
"Region: ", df1$Region)
) %>%
add_lines(data=df1, x = ~GDP_per_Capita, y = fitted(lr1),
line = list(width = 0.5, dash = "dot", color="red")) %>%
layout(showlegend = TRUE,
legend = list(orientation = 'l'),
title="Top Universities vs GDP per Capita",
xaxis=list(title="GDP per Capita", showgrid = T),
yaxis=list(title="Top 1000 University per million Population", showgrid = T))
@AmadeusNing 你基本上就在那里。 Plotly 可讓您“配置”每條跡線及其隨附的圖例(包括將其與其他跡線結合)。 您可以使用跟蹤調用中的 showlegend 參數輕松解決此問題。 要刪除圖例:showlegend = FALSE。
我沒有你的數據,所以我恢復到經典的 mpg 數據集並為該線定義一個簡單的線性回歸。 我還在示例圖中強調了線寬以進行演示。
# define a regression line
lr <- lm(hwy ~ displ, mpg)
# draw basis plotly plot, create grouping by setting cyl as factor
fig1 <- plot_ly(data = mpg, x = ~displ, y = ~hwy, color = ~as.factor(cyl)
, type = "scatter", mode = "markers")
# add regression line
fig1 <- fig1 %>%
add_lines(data=mpg %>% group_by(cyl), x = ~displ, y = fitted(lr)
, line = list(width = 2, dash = "dot", color="red")
#----------------- remove legend for line - comment out to see it displayed
, showlegend = FALSE
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.