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):
ggplotly(p)
(title alignment not preserved):
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With