tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.48k stars 2.02k forks source link

Problem of hjust in legend.text in ggplot2 v3.5.0 #5835

Closed lcpmgh closed 5 months ago

lcpmgh commented 5 months ago

After updating to version 3.5.0, I attempted to adjust the distance between the legend keys and labels using hjust. However, only some of the text shifted, and the movement’s occurrence and scale seemed to be related to the content of the text. I suspect this might be a bug. By the way, I learned from other users that using margin can perfectly adjust the distance between keys and labels.

For the problem I mentioned, here is a simplified example:

# Figure 1
dt <- data.frame(x=c("a","b","cc","d"), y=c(1,2,3,4))
ggplot(dt, aes(x, y, fill=x))+
  geom_bar(stat = "identity")+
  theme(legend.text = element_text(hjust = 3))

# Figure 2
dt <- data.frame(x=c("ab","bb","dc","ds"), y=c(1,2,3,4))
ggplot(dt, aes(x, y, fill=x))+
  geom_bar(stat = "identity")+
  theme(legend.text = element_text(hjust = 15))

fig

teunbrand commented 5 months ago

Hi there, thanks for the report! I don't quite understand why the text is positioned this way in your example, but for increasing the space you should indeed use the element_text(margin) setting. The hjust setting should typically be between 0 and 1 and while hjust = 15 is accepted, how it is interpreted might depend on circumstances.

teunbrand commented 5 months ago

I'm closing this issue as the problem of spacing text from their keys has a better solution than using hjust.