簡體   English   中英

R ggplotly 還原 ggplot2 中的圖例名稱更改

[英]R ggplotly reverts legend name changes in ggplot2

根據下面的數據和代碼, ggplotlylegend labels更改回列值。

我確實找到了解決方案,但這需要添加一個新列。 有沒有辦法在不修改數據的情況下做到這一點?

盡管使用 scale_fill_manual(),ggplotly() 仍忽略圖例標簽編輯

數據( pop_gen_df ):

structure(list(age_group = c("<  5 years", "5 - 14", "15  -  24", 
"25  -  34", "35  -  44", "45  -  54", "55  -  64", "65  -  74", 
"75  -  84", "85 +", "<  5 years", "5 - 14", "15  -  24", "25  -  34", 
"35  -  44", "45  -  54", "55  -  64", "65  -  74", "75  -  84", 
"85 +"), Type = c("males", "males", "males", "males", "males", 
"males", "males", "males", "males", "males", "females", "females", 
"females", "females", "females", "females", "females", "females", 
"females", "females"), Value = c(-6, -13, -13, -15, -17, -15, 
-11, -6, -3, -1, 6, 12, 12, 14, 16, 15, 12, 7, 4, 2)), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))

代碼:

# Plot
gg_pop_hisp = ggplot(pop_hisp_df, aes( x = forcats::as_factor(age_group), y = Value, fill = Type)) +
  geom_bar(data = subset(pop_hisp_df, Type == "females"), stat = "identity") + 
  geom_bar(data = subset(pop_hisp_df, Type == "males"), stat = "identity") + 
  scale_y_continuous(labels = function(z) paste0(abs(z), "%")) +          # CHANGE
  scale_fill_manual(name = "", values = c("females"="#FC921F", "males"="#149ECE"), labels = c("Females", "Males")) +
  ggtitle("HISPANIC POPULATION BY GENDER AND AGE GROUP") +
  labs(x = "PERCENTAGE POPULATION", y = "AGE GROUPS", fill = "Gender") +
  theme_minimal() +
  theme(legend.position="bottom") +
  coord_flip()

# Interactive and place legend at the bottom
ggplotly(gg_pop_hisp) %>% 
  layout(
    legend = list(
      orientation = 'h', x = 0.3, y = -0.1, 
      title = list(text = '')
      )
    )

我不確定這是否屬於“不修改數據”,而是修改了用於定義美學的數據。

在定義fill美學並在那里定義標簽時,傳遞Type作為一個因素。 您不再需要在scale_fill_manual和 plotly 中顯式添加標簽,但您需要更新顏色映射以使用大寫版本的標簽。

gg_pop_hisp = ggplot(
  pop_hisp_df, 
  aes( 
    x = forcats::as_factor(age_group), 
    y = Value, 
    # explicitly define fill using a factor to define the labels
    fill = factor(
      Type, levels = c("females", "males"), labels = c("Females", "Males")
    )
  )
) +
  geom_bar(data = subset(pop_hisp_df, Type == "females"), stat = "identity") + 
  geom_bar(data = subset(pop_hisp_df, Type == "males"), stat = "identity") + 
  scale_y_continuous(labels = function(z) paste0(abs(z), "%")) +          
  
  # Update the color mappings to use the new labels
  # No need for the labels arguement because it's taken from the factor labels
  scale_fill_manual(name = "", values = c("Females"="#FC921F", "Males"="#149ECE")) +
  
  ggtitle("HISPANIC POPULATION BY GENDER AND AGE GROUP") +
  labs(x = "PERCENTAGE POPULATION", y = "AGE GROUPS", fill = "Gender") +
  theme_minimal() +
  theme(legend.position="bottom") +
  coord_flip()

暫無
暫無

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

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