简体   繁体   中英

How to make an interactive donut chart with ggplot2 & plotly?

Hello I have a simple donut chart that I can make with ggplot2.

data <- data.frame(
  category=c("Grants", "Private", "Income"),
  amount=c(400000, 123251, 37292)
)

# Compute percentages
data$fraction = data$amount / sum(data$amount)

# Compute the cumulative percentages (top of each rectangle)
data$ymax = cumsum(data$fraction)

# Compute the bottom of each rectangle
data$ymin = c(0, head(data$ymax, n=-1))
 
# Make the plot

ggplot(data, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) +
     geom_rect() +
     coord_polar(theta="y") + 
     xlim(c(2, 4)) +
     theme_void() + 
     theme(legend.position = "bottom") + 
     theme(legend.title=element_blank())

Which yields this nice chart

在此处输入图像描述

But when I wrap it around with ggplotly() I get a misformed chart

在此处输入图像描述

What am I doing wrong? I really just want a donut chart that I can hover over.

Just make it using plotly ( https://plotly.com/r/pie-charts/ )?

data <- data.frame(
    category=c("Grants", "Private", "Income"),
    amount=c(400000, 123251, 37292)
)

# Compute percentages
data$fraction = data$amount / sum(data$amount)

# Compute the cumulative percentages (top of each rectangle)
data$ymax = cumsum(data$fraction)

# Compute the bottom of each rectangle
data$ymin = c(0, head(data$ymax, n=-1))

# Make the plot
library(plotly)
library(dplyr)

# Get Manufacturer

data <- data %>% group_by(category)
fig <- data %>% plot_ly(labels = ~category, values = ~fraction)
fig <- fig %>% add_pie(hole = 0.6)
fig <- fig %>% layout(showlegend = T,
                      xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
                      yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

fig

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM