Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R plotly ignoring text label alignment hjust

I am using plotly 4.8 with ggplot2 3.0.0, and trying to add and align text labels to my scatter plots. However, it seems the hjust parameter is being ignored by plotly in geom_text(aes(....), hjust = "left"). (Also tried hjust = 0.)

GGPLOT OUTPUT

See it renders fine in plot window as a ggplot with labels left aligned.

ggplot left align chart example

PLOTLY OUTPUT

But the alignment is lost in conversion, and the text is centered.

plotly center chart example

So the question, is fixing this alignment possible with plotly?

TEST EXAMPLE CODE

library(ggplot2)
library(data.table)
library(plotly)

data(mtcars)

plotdata <- as.data.table(mtcars)
plotdata$carname <- rownames(mtcars)

# take a small demo subset
plotdata <- plotdata[1:10,]

gg <- ggplot(plotdata, aes(x = wt, y = mpg, label = carname)) +  
               geom_point()  + theme_minimal()
gg <- gg + geom_text(aes(label = carname),
                       size = 2,
                       hjust = "left")
print(gg)

# convert ggplot
p <- ggplotly(gg)
p
like image 270
micstr Avatar asked Aug 29 '18 12:08

micstr


1 Answers

You just need to add text position textposition = "right":

ggplotly(p) %>% style(textposition = "right")

Output:

Output from Plotly

Ref: https://github.com/ropensci/plotly/issues/769

like image 185
Saurabh Chauhan Avatar answered Nov 15 '22 06:11

Saurabh Chauhan