【问题标题】:labels in bar chart touches the top horizontal line条形图中的标签触及顶部水平线
【发布时间】:2020-03-03 23:35:00
【问题描述】:

我正在尝试在闪亮的上下文中创建条形图。一切看起来都不错,除了标签。如下图所示,一些标签隐藏在顶部水平线的后面。

    Diff_plot <- reactive({
    ggplot(Diff_data(), aes(x =Difficulty_Type, y = Percentage, fill=County.y)) + geom_bar(stat =
                                                                       "identity",
                                                                       position = position_dodge()
             ) +

      scale_fill_manual(values=cbbPalette)+

      geom_text(
        aes(label = Percentage2),
        vjust = 0,
        colour = "black", 
        position = position_dodge(width=0.9),
        fontface = "bold",
        size=4,
        angle = 90,
        hjust = 0
      ) + 
      labs(
        x = "",
        y = "Frequecny",

        face = "bold"
      ) +
      theme_bw() + scale_y_continuous(labels = scales::comma) +
      theme(plot.title = element_text(
        hjust = 0.5,
        size = 15,
        colour = "Black",
        face = "bold"
      )

【问题讨论】:

    标签: r ggplot2 geom-text


    【解决方案1】:

    您可以使用hjustvjust 的组合将文本设置在条形图的顶部。

    使用hjust = -1,您将在条形图顶部和文本之间获得更多空间。如果您的文本被顶部水平线隐藏,您可以使用 ylim 增加 y 轴的限制

    df <- data.frame(X = LETTERS[1:3],
                     Y = sample(1:10,3),
                     labels = letters[4:6])
    
    library(ggplot2)
    ggplot(df,aes(x = X, y = Y, label = labels))+
      geom_col()+
      geom_text(angle = 90, hjust = -1, vjust = 0.5)+
      ylim(0,6.5)
    

    【讨论】:

    • 谢谢。有没有办法将 ylim 定义为 y 值的最大值加上一些常数值的函数。像这样:ylim (0, Max Y+5)。另外,我想知道是否可以将此声明与您提出的声明结合起来: scale_y_continuous(labels = scales::comma)
    • 当然,在scale_y_continuous 中,您可以添加参数limits,这与ylim 相同。您可以定义 y 限制,例如:limits = c(0, max(df$y)*0.5)。它回答了你的问题吗?
    • scale_y_continuous 中,您也可以使用expand 选项。这会在数据周围添加一些填充。
    • 谢谢你们。我在语法中添加了 limits = c(0, max(df$y)*0.5) 并出现错误。另外,尝试了 limits = c(0, 1) 但得到了错误:二进制运算符的非数字参数。
    • 您能否编辑您的问题以添加您的数据集的可重现示例以便我们对其进行测试?比如dput(NameofYourDataframe)(见这里:stackoverflow.com/questions/5963269/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多