R ggplot2实验室左对齐和数据排序

R ggplot2实验室左对齐和数据排序,r,ggplot2,R,Ggplot2,我对使用ggplot2软件包创建的绘图有一个问题。假设我们有这样一个情节: df = data.frame( numbers = seq(1,5), labels = c( "Brand", "Good Brand", "The Best Brand", "The Best Brand Today", "The Best Brand This Month" ) ) df = df[order(-df$numbers),] plot = ggpl

我对使用ggplot2软件包创建的绘图有一个问题。假设我们有这样一个情节:

df = data.frame(
  numbers = seq(1,5),
  labels = c(
    "Brand",
    "Good Brand",
    "The Best Brand",
    "The Best Brand Today",
    "The Best Brand This Month"
  )
)
df = df[order(-df$numbers),]
plot = ggplot(data = df, aes(x=labels, y=numbers))+
  geom_bar(stat="identity", fill='orange')+
  coord_flip()+
  labs(
    title = "Exemplary title",
    caption = "Exemplary caption 1\nExemplary caption number 2"
  )+
  theme(
    plot.title = element_text(hjust = -0.5),
    plot.caption = element_text(hjust = -0.5),
    panel.spacing = unit(c(0,0,0,20), "cm")
  )
plot
我的情况如下:

  • title
    caption
    设置负值
    vjust
    并不是最好的解决方案,原因有二:
    • 如果标题有
      \n
      字符,则其格式非常奇怪,似乎取决于标题长度
    • 标题长度可以更改,因此vjust值也可以更改,因此它们不能是常量
  • 有没有更好的方法将标题和标题对齐到绘图的左侧(在本例中,对齐到整个图片的左侧)

  • 为什么ggplot总是按照标签的字母顺序对数据进行排序?在绘图时,是否可以考虑之前完成的df排序?它能比使用
    x=reorder(标签、数字)
    更好地解决吗

  • 使用
    hjust=0
    进行左对齐。无论长度如何,它们都会排成一行,您的问题是
    -0.5
    。至于排序,所有因素都有一个隐式顺序,默认为字母顺序
    ggplot
    不排序,它使用已经存在的排序,编码在因子级别中。事实上,如果你想要一个不同的顺序,你必须改变因子水平的顺序。这可以通过多种方式实现,
    reorder
    如果您希望通过其他变量对其进行排序,则很好。在大多数其他情况下,直接设置
    级别
    很好。@Gregor Making
    vjust=0
    是不够的,然后它们与Y轴对齐。我需要一个解决方案,将实验室与整个画面的左侧对齐(从“世界上最好的品牌”开始)。然后我会尝试
    cowplot
    package。ggplot路线基于打印区域。而
    hjust
    的工作方式是0.5是从左对齐到中心对齐所需的距离-这取决于字符串中字符的宽度。