如何在绘制的条形图中对相同的因素进行分组

问题描述 投票:0回答:1

尝试将分组的因素绘制在簇中,例如每年的所有“低点”在一起,每年的所有“中度”在一起等等,并使用图例来为年份着色。 Dplyr 分组不按类型分组,如 group_by(Type) 和 group_by(Year) 中返回相同的数据帧。我错过了什么?

# create dataframe
year <- 2020
low <- 45
medium <- 52
high <- 98
df <- data.frame(year, low, medium, high)

year <- 2021
low <- 60
medium <- 83
high <- 80
df2 <- data.frame(year, low, medium, high)

year <- 2022
low <- 64
medium <- 34
high <- 20
df3 <- data.frame(year, low, medium, high)

year <- 2023
low <- 62
medium <- 47
high <- 58
df4 <- data.frame(year, low, medium, high)

test <- rbind(df, df2, df3, df4)
test <- test %>% pivot_longer(!year, names_to="Type", values_to = "total")

library(highcharter)

highchart() %>%


hc_chart(type = "column") %>%
  hc_add_series(name = "Type" , data = test$total , color ="green" )%>%
  hc_xAxis(categories = test$Type)%>% 
  hc_xAxis(title = list(text = "Type"))%>%
  hc_yAxis(title = list(text = "GWh"))%>%
  hc_title(text= "Types Year Comparison") %>% 
  hc_subtitle(text= "test") %>% 
  hc_caption(text= "Based on year 2007 population")%>% 
  hc_legend(enabled= FALSE)
r dplyr r-highcharter
1个回答
0
投票

尝试将

Type
作为因子,将
year
作为字符:

# Original data
test <- tibble::tribble(
  ~year,    ~Type, ~total,
  2020,    "low",     45,
  2020, "medium",     52,
  2020,   "high",     98,
  2021,    "low",     60,
  2021, "medium",     83,
  2021,   "high",     80,
  2022,    "low",     64,
  2022, "medium",     34,
  2022,   "high",     20,
  2023,    "low",     62,
  2023, "medium",     47,
  2023,   "high",     58)

# Adjust type and year
test <- mutate(test, Type = fct(Type), year = as.character(year)) 

# The plot
test %>% 
  hchart("column", hcaes(x = Type, y = total, group = year)) %>% 
  hc_yAxis(title = list(text = "GWh"))%>%
  hc_title(text= "Types Year Comparison") %>% 
  hc_subtitle(text= "test") %>% 
  hc_caption(text= "Based on year 2007 population")%>% 
  hc_legend(enabled= FALSE)

绘图输出:

© www.soinside.com 2019 - 2024. All rights reserved.