簡體   English   中英

R ggplot2 創建帶百分比的金字塔 plot

[英]R ggplot2 create a pyramid plot with percentages

根據下面的代碼,我正在嘗試創建一個pyramid plot Value列以百分比表示,因此我在此列中添加了%符號。 而且,現在代碼不起作用。

Error: Discrete value supplied to continuous scale

添加%符號的原因是這樣它也將出現在 x 軸標簽中。

如何解決此問題,以使%符號出現在 x 軸上,而-符號也不會出現在 x 軸上?

代碼+數據:

library(tidyverse)

# Data
pop = sstructure(list(age_group = c("<  5 years", "5 - 9", "10 - 14", 
"15  -  19", "20  -  24", "25  -  29", "30  -  34", "35  -  44", 
"45  -  54", "55  -  64", "65  -  74", "75  -  84", "85 +"), 
    males = c(6, 6, 7, 6, 7, 7, 8, 17, 15, 11, 6, 3, 1), females = c(6, 
    5, 6, 6, 6, 7, 7, 16, 15, 12, 7, 4, 2)), row.names = c(NA, 
-13L), spec = structure(list(cols = list(`AGE GROUP` = structure(list(), class = c("collector_character", 
"collector")), MALES = structure(list(), class = c("collector_double", 
"collector")), FEMALES = structure(list(), class = c("collector_double", 
"collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x0000029a145331e0>, class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"))

# Draw a pyramid plot

# Clean data
pop_df = pop %>% select(age_group,
                        males,
                        females) %>% 
                 gather(key = Type, value = Value, -c(age_group))

# Make male values negative
pop_df$Value = ifelse(pop_df$Type == "males", -1*pop_df$Value, pop_df$Value)

# Add % sign to the Value column
pop_df$Value = paste0(pop_df$Value, "%")


# Plot
gg_pop = ggplot(pop_df, aes(x = age_group, y = Value, fill = Type)) +
  geom_bar(data = subset(pop_df, Type == "females"), stat = "identity") + 
  geom_bar(data = subset(pop_df, Type == "males"), stat = "identity") + 
  scale_y_continuous(labels = abs) +
  ggtitle("Male vs Female Population Comparison") +
  labs(x = "Age group", y = "Percentage", fill = "Gender") +
  coord_flip() 

# Interactive
ggplotly(gg_pop)

列數據不要加% ,在label中加。

ggplot(pop_df, aes(x = age_group, y = Value, fill = Type)) +
  geom_bar(data = subset(pop_df, Type == "females"), stat = "identity") + 
  geom_bar(data = subset(pop_df, Type == "males"), stat = "identity") + 
  scale_y_continuous(labels = function(z) paste0(abs(z), "%")) +          # CHANGE
  ggtitle("Male vs Female Population Comparison") +
  labs(x = "Age group", y = "Percentage", fill = "Gender") +
  coord_flip() 

ggplot 在軸標簽中帶有 %

暫無
暫無

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

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