Search code examples
rplotly

Setting a legend and Donut Plot


I working with Plotly and I trying to make a Donut plot. Below you can see my data.

library(plotly)
library(reshape2)
library(dplyr)

df<-data.frame(city=c("NYC-The written history of New York City began with the first European explorer, the Italian Giovanni da Verrazzano in 1524. European settlement began with the Dutch in 1608.",
                      "Seattle-Seattle is a seaport city on the West Coast of the United States. It is the seat of King County, Washington. ",
                      "Boston",
                      "LA",
                      "Miami",
                      "Washington"),
               value=c(100,200,300,400,500,600))

df <-melt(df)

fig<-df %>% 
  plot_ly(labels = ~city, values = ~value)
fig <- fig %>% add_pie(hole = 0.6)
fig <- fig%>% layout(title = "Comparison between of the cities ")

fig

Data is a little bit specific because it contains columns with around 170 characters. When I made the Donut plot, the legend is too big due to the characters and the chart is too small. Below you can see how it look like this Donut Plot.

enter image description here

So can anybody help me how to make this legend smaller, chart bigger and same title ( with same font) ?


Solution

  • You can add some \n enters in your big legend text and change the font size like this:

    library(plotly)
    library(reshape2)
    library(dplyr)
    
    df<-data.frame(city=c("NYC-The written history of New York City began with the first European explorer, \n the Italian Giovanni da Verrazzano in 1524. \n European settlement began with the Dutch in 1608.",
                          "Seattle-Seattle is a seaport city on the West Coast of the United States. \n It is the seat of King County, Washington. ",
                          "Boston",
                          "LA",
                          "Miami",
                          "Washington"),
                   value=c(100,200,300,400,500,600))
    
    df <-melt(df)
    
    fig<-df %>% 
      plot_ly(labels = ~city, values = ~value)
    fig <- fig %>% add_pie(hole = 0.6)
    fig <- fig%>% layout(title = "Comparison between of the cities ",
                         legend = list(font=list(size = 7)))
    
    fig
    

    Output:

    enter image description here