Highcharter库如何制作半圆甜甜圈?

时间:2019-11-04 08:37:04

标签: r pie-chart r-highcharter

我正在尝试使用highcharter库制作半圆形的甜甜圈,但我只知道如何制作饼图。我知道使用JS可以通过添加“ startAngle”和“ endAngle”来实现,但是我想知道如何使用R:

A <- c("a", "b", "c", "d")
B <- c(4, 6, 9, 2)

C <- c(23, 26, 13, 15)
df <- data.frame(A, B, C)

highchart() %>% 
  hc_chart(type = "pie") %>% 
  hc_add_series_labels_values(labels = df$A, values = df$B)%>%    

  hc_tooltip(crosshairs = TRUE, borderWidth = 5, sort = TRUE, shared = TRUE, table = TRUE,
             pointFormat = paste('<b>{point.percentage:.1f}%</b>')
  ) %>%

  hc_title(text = "ABC",
           margin = 20,
           style = list(color = "#144746", useHTML = TRUE))

enter image description here

谢谢!

2 个答案:

答案 0 :(得分:1)

尽管不使用Highcharts库,您仍可以执行类似的操作。

library(tidyverse)
library(ggforce)
library(scales)
library(ggplot2)

# -------------------------------------------------------------------------

A <- c("a", "b", "c", "d")
B <- c(4, 6, 9, 2)

C <- c(23, 26, 13, 15)
df <- data.frame(A, B, C)

# Ensure A is a factor (we'll be using it to fill the pie)
df$A <- factor(df$A)

# compute the individual proportion in this case using var C
df$prop <- df$C/sum(df$C) 

# compute the cumulative proportion and use that to plot ymax 
df$p_end <- cumsum(df$prop)

# generate a y-min between 0 and 1 less value than p_end (using p_end) 
df$p_start <- c(0, head(df$p_end ,-1))



# -------------------------------------------------------------------------

# plot 
df %>%
  mutate_at(c("p_start", "p_end"), rescale, to=pi*c(-.5,.5), from=0:1) %>%
  ggplot + 
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = .5, r = 1, start = p_start, end = p_end, fill=A)) + 
  coord_fixed() +xlab("X_label") + ylab("Y_lablel") + guides(fill=guide_legend(title="Legend Title"))


输出

pit_chart

希望有帮助。

答案 1 :(得分:1)

尝试在startAngle = -90, endAngle = 90内添加hc_add_series_labels_values

不建议使用警告hc_add_series_labels_values,因此建议使用hc_add_series

highchart() %>%
  hc_add_series(type = "pie", data = df, hcaes(x = A, y = B), startAngle = -90, endAngle = 90) %>%
  hc_tooltip(pointFormat = '<b>{point.percentage:.1f}%</b>') %>%
  hc_title(text = "ABC",
           margin = 20,
           style = list(color = "#144746", useHTML = TRUE))

enter image description here