Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left-align chart title in plotly

Tags:

r

ggplot2

plotly

How can I left-align the chart title in a plot_ly object (as created from ggplotly)?

library(ggplot2)
library(plotly)

p <-
  ggplot(mtcars, aes(mpg, cyl)) + 
  geom_point() + 
  ggtitle("My Title") + 
  # Not necessary by default:
  theme(plot.title = element_text(hjust = 0.0))

p

ggplotly(p)

Output of p (intended title alignment):

enter image description here

ggplotly(p) (title alignment not preserved):

enter image description here

like image 889
Hugh Avatar asked Jun 23 '17 03:06

Hugh


People also ask

How do I change the position of my title in Plotly?

In order to align titles in visualization using plotly module, we are going to use the update_layout() method. Parameters: title: Accepts string value as the title of the visualization. title_x: This parameter is used to align the title in a horizontal motion and accepts a value from 0 to 1.

How do you add labels in Plotly?

As a general rule, there are two ways to add text labels to figures: Certain trace types, notably in the scatter family (e.g. scatter , scatter3d , scattergeo etc), support a text attribute, and can be displayed with or without markers. Standalone text annotations can be added to figures using fig.


2 Answers

plot_ly has added this functionality. Now you can call:

ggplotly(p) %>%
  layout(
    title = list(
      xanchor = "right"
    )
  )

or

ggplotly(p) %>%
  layout(
    title = list(
      x = 0.1
    )
  )

where x is the normalized position, with x=0 positioning all the way to the left and x=1 positioning all the way to the right.

like image 108
Wil Avatar answered Oct 21 '22 18:10

Wil


You could do

ggplotly(p) %>%
  add_annotations(
    yref="paper", 
    xref="paper", 
    y=1.15, 
    x=0, 
    text="My Title", 
    showarrow=F, 
    font=list(size=17)
  ) %>% 
  layout(title=FALSE)
like image 39
lukeA Avatar answered Oct 21 '22 19:10

lukeA