How to horizontally center a pie chart with plotly in R? - r

I'm new to plotly, trying to figure out how to get a piechart to be aligned at the center of the entire plot area.
library(dplyr)
library(plotly)
data_for_plot <-
mtcars %>%
count(cyl)
> data_for_plot
## cyl n
## 1 4 11
## 2 6 7
## 3 8 14
plot_ly(data_for_plot, labels = ~cyl, values = ~n, type = 'pie', hole = 0.05 ,textposition = 'outside',textinfo = 'percent') %>%
layout(title = list(text = "my nice title is here", xanchor = "center"),
showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE)) %>%
layout(paper_bgcolor = "pink")
So I get this pie chart, which is not centered:
I assume that inside layout() I need something that refers to the piechart itself, to assign it with xanchor = "center". But I researched this and couldn't find an answer.
Update on my attempts - 2020-01-18
I've tested the majority of attributes in layout() and still couldn't find something that would work with xanchor = "center". I've alse examined plotly's reference guide but so far to no avail.

Seems that the solution involves setting up the margin attribute within layout(). The solution is based on this hint, referring to this post. Implementing this to R is done using the following code:
plot_ly(data_for_plot, labels = ~cyl, values = ~n, type = 'pie', hole = 0.05 ,textposition = 'outside',textinfo = 'percent') %>%
layout(title = list(text = "my nice title is here", xanchor = "center"),
showlegend = F,
margin = list(l = 20, r = 20),
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE)) %>%
layout(paper_bgcolor = "pink")

Related

Trouble with creating bar & pie subplot with R plotly

I've created a Plotly bar and pie chart and want to combine them to form one chart.
When I use subplot() to combine these Plotly charts, the pie & bar charts overlap.
Any advice on how to present these plots so that each is in its own row? Thank you.
Here's a picture of what I'm currently experiencing:
Reprex below:
#Pie chart example
pie_tibble <- tibble(donuts = c(49050, 66924),
group = c("Group A", "Group B"))
pie <- plot_ly(data = pie_tibble, labels = ~group, values = ~donuts, type = 'pie',
showlegend = F,
hoverinfo = "none",
marker = ~list(colors = c('#404040', '#24608B'))) %>%
layout(xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
bar_tibble <- tibble(category = c("Cat 1", "Cat 1", "Cat 2", "Cat 2"),
pct_increase = c(0.17, 0.25, 0.64, 0.85),
week = c(1, 2, 1, 2))
#Bar chart example
bar <- plot_ly(data = bar_tibble, hoverinfo = "none") %>%
layout(
barmode = 'stack',
showlegend = F) %>%
add_trace(
x = ~pct_increase,
y = ~category,
type = "bar",
transforms = list(
list(
type = "aggregate",
groups = ~category,
aggregations = list(
list(
target = "x", func = "avg", enabled = T)))))
#Combine charts
subplot(bar, pie, nrows = 2)
Pie charts and plotly::subplot() are notoriously challenging - though you can get around many of the issues by specifying the domain manually. Below I have changed the pie code by specifying the domain = list(...) as so:
pie <- plot_ly(data = pie_tibble, labels = ~group, values = ~donuts, type = 'pie',
# Specify the domain here
domain = list(x = c(0.5, 0.5), # centered on x axis
y = c(0.0, 0.4)),
showlegend = F,
hoverinfo = "none",
marker = ~list(colors = c('#404040', '#24608B'))) %>%
layout(xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
subplot(bar, pie, nrows = 2) now gives:
Sorry I don't have a more elegant answer, but hoping someone else might!

How to hard code the color for the displayed variable in plotly pie chart?

Do we have something similar to our ggplot where
we define the color panel for each variable ?
scale_manual <- function(...){
ggplot2::manual_scale(
"fill",
values = setnames(c("green","red","blue","yellow","grey"),
c("var1","var2","var3","var4","var5")),
...
)
}
Although this Q seems to answer,
How can I change the colors of the slices in pie charts in plotly for r using hexadecimal strings?
but it is not working here.
Please consider an reprex below:
library(plotly)
USPersonalExpenditure <- data.frame("Categorie"=rownames(USPersonalExpenditure), USPersonalExpenditure)
data <- USPersonalExpenditure[,c('Categorie', 'X1960')]
p <- plot_ly(data, labels = ~Categorie, values = ~X1960, type = 'pie') %>%
layout(title = 'United States Personal Expenditures by Categories in 1960',
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
#trial 1
plot_ly(data, labels = ~Categorie, values = ~X1960, type = 'pie', marker = list(color = rainbow(5))) %>%
layout(title = 'United States Personal Expenditures by Categories in 1960',
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
# trial 2
plot_ly(data, labels = ~Categorie, values = ~X1960, type = 'pie', marker = list(color = brewer_pal(5, "Set3"))) %>%
layout(title = 'United States Personal Expenditures by Categories in 1960',
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
Since there are many plots using the same data,
color need to be consistent.
So, trying to hard code for each variable.
I usually use Color mapping functions from the leaflet package before making interactive plots for shiny apps and plotly charts:
Hard code the color variable using your desired palette.
data$color <- leaflet::colorFactor(
palette = "Dark2", domain = data$Categorie
)(data$Categorie)
plot_ly(
data, labels = ~Categorie, values = ~X1960, type = 'pie',
marker = list( colors = ~color)
) %>%
layout(
title = 'United States Personal Expenditures by Categories in 1960',
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)
)
You may also hardcode it manually:
colors_list <- list(
"Food and Tobacco" = "#1B9E77",
"Household Operation" = "#D95F02",
"Medical and Health" = "#7570B3",
"Personal Care" = "#E7298A",
"Private Education" = "#66A61E"
)
data$color <- dplyr::recode(data$Categorie, !!!colors_list)
plot_ly(
data, labels = ~Categorie, values = ~X1960, type = 'pie',
marker = list( colors = ~color)
) %>%
layout(
title = 'United States Personal Expenditures by Categories in 1960',
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)
)

Rounding off percentages in plotly pie charts

label=c("<25%","25 - 50%",">75%")
values=c(4,2,3)
df=data.frame(label,values)
plot_ly(df, labels = ~label, values = ~values,text=values,textposition="auto", type = 'pie') %>%layout(title = 'Percentage Effort time',showlegend=T,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
When I run this code, I get a pie chart with percentages and the numbers. How can I obtain percentages that are rounded off to whole numbers instead of decimal points?
You can use textinfo='text' to hide the percent values and provide a custom formatted label with text:
text = ~paste(round((values / sum(values))*100, 0)),
textinfo='text',
Complete example:
library(magrittr)
library(plotly)
label=c("<25%","25 - 50%",">75%")
values=c(4,2,3)
df=data.frame(label,values)
plot_ly(df,
labels = ~label,
values = ~values,
text = ~paste(round((values / sum(values))*100, 0)),
#textinfo='none',
#textinfo='label+value+percent',
textinfo='text',
textposition="auto", type = 'pie') %>% layout(title = 'Percentage Effort time', showlegend=T,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)
)
A newer method for if you'd like to avoid creating a text template to 'overwrite' the values shown in the default way (works in python):
fig.update_traces(
textposition="outside",
texttemplate="%{label} (%{percent:.1%f})",
...
Th2 ':.1%f' portion will round values to 1 decimal place, while ':.0%f' will give values rounded to whole numbers
This would give you 2 digits rounded percentage, with value shown multiply by 100 and suffix with "%":
texttemplate = '%{text:.2p}'
Here is the complete reference of d3-format's syntax I found in the documentation.

Placing donut charts side by side using plotly in R

I have created donut charts from plotly from the following:
library(plotly)
library(RColorBrewer)
test<-data_frame(Score=c("Green","Green","Yellow","Yellow","Clear","Clear","Red","Red"),Lang=c(rep("Eng",4),rep("Esp",4)))
test1<-data_frame(Score=c("Green","Yellow","Yellow","Yellow","Clear","Clear","Red","Red"),Lang=c(rep("Eng",4),rep("Esp",4)))
color_order<-c("Green","Clear","Yellow","Red")
colors<-c("#31a354","#bdbdbd","#fec44f","#de2d26")
a<-test %>%
mutate(Score=factor(Score,levels=color_order))%>%
arrange(Score)%>%
group_by(Score)%>%
summarize(count = n()) %>%
plot_ly(labels = ~Score,
values = ~count,
hoverinfo="skip",
text = ~count,
marker = list(colors = colors),
legendgroup = ~Score) %>%
add_pie(hole = 0.6) %>%
layout(title = "test chart1", showlegend = TRUE,
font=list(family="sans serif",color="#000"),
plot_bgcolor="#f0f0f0",
legend = list(orientation = 'h',font=list(size=28)),
xaxis = list(title=paste0("Total: ",nrow(test)), showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
b<-test1 %>%
mutate(Score=factor(Score,levels=color_order))%>%
arrange(Score)%>%
group_by(Score)%>%
summarize(count = n()) %>%
plot_ly(labels = ~Score,
values = ~count,
hoverinfo="skip",
text = ~count,
marker = list(colors = colors),
legendgroup = ~Score) %>%
add_pie(hole = 0.6) %>%
layout(title = "test chart2", showlegend = FALSE,
font=list(family="sans serif",color="#000"),
plot_bgcolor="#f0f0f0",
legend = list(orientation = 'h',font=list(size=28)),
xaxis = list(title=paste0("Total: ",nrow(test1)),showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
I am attempting to put them side by side with the common legend from plot a, and I run the following:
subplot(a,b,nrows = 1)
However, I only see one plot which appears to be a combination of the two. I also tried the approach here: Plotly: Bar and pie charts side by side, but it just gave me inception style donut within a donut. How can I put them next to each other with the common legend? Thanks.
According to this (https://plot.ly/r/pie-charts/), in order to create pie chart subplots, you need to use the domain attribute. You could try something like this (adjust domain for your needs):
a <- test %>%
mutate(Score=factor(Score,levels=color_order))%>%
arrange(Score)%>%
group_by(Score)%>%
summarize(count = n())
b<-test1 %>%
mutate(Score=factor(Score,levels=color_order))%>%
arrange(Score)%>%
group_by(Score)%>%
summarize(count = n())
p <- plot_ly() %>%
add_pie(data = a, labels = ~Score, values = ~count, hole = 0.6,
name = "a", domain = list(x = c(0, 0.4), y = c(0.4, 1))) %>%
add_pie(data = b, labels = ~Score, values = ~count, hole = 0.6,
name = "b", domain = list(x = c(0.6, 1), y = c(0.4, 1))) %>%
layout(title = "test chart1", showlegend = TRUE,
font=list(family="sans serif",color="#000"),
plot_bgcolor="#f0f0f0",
legend = list(orientation = 'h',font=list(size=28)),
xaxis = list(title=paste0("Total: ",nrow(test)), showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

Plotly axis labels on multiple lines alignment

I'm building a Shiny application with some Plotly horizontal bar charts. Some data labels are pretty long and I want to break them on multiple lines. It works when places <br> on the place I want to break the line, but alignment of the axis labels does not go well. See picture below of output (left) and desired plot (right).
Below a minimal working example. It left out the Shiny part, because I expect that this does not affect the possible solution.
df <- data.frame(
name = paste0('This is a pretty long sentence',1:10),
dimA = 1:10
)
df$name <- gsub('This is a pretty long sentence','This is a<br>pretty long<br>sentence',df$name)
## Hide axes
ax <- list(
title = "",
showline = FALSE,
showticklabels = FALSE,
showgrid = FALSE,
domain = list(0.2, 1)
)
ay <- list(
title = "",
zeroline = FALSE,
showline = FALSE,
showticklabels = TRUE,
showgrid = FALSE
)
p <- df %>%
plot_ly(x = ~dimA,
y = ~name,
type = 'bar',
orientation = 'h'
) %>%
layout(xaxis = ax, yaxis = ay)
p
Help is highly appreciated! Struggling with this for hours, but unable to find a solution!
This is not very general but you can adjust the tick position using tickvals, for example:
ay <- list(
title = "",
zeroline = FALSE,
showline = FALSE,
showticklabels = TRUE,
showgrid = FALSE,
tickvals = 0:9 + 0.25
)

Resources