【问题标题】:ggplotly in R : change data label sizeR中的ggplotly:更改数据标签大小
【发布时间】:2019-08-12 10:21:00
【问题描述】:

我必须将ggplot 转换为plotly。当然,最简单的方法似乎是使用ggploty,但字体大小会发生变化。恢复轴标签和标题的合适大小没问题,但我不知道如何为数据标签做到这一点?有任何想法吗?我更喜欢保留ggplot 并用ggplotly 包裹它(还有许多其他情节)。

我尝试了布局中的字体,但没有成功:

library(ggplot2)
library(plotly)

tbl <- data.frame(
  indicateur = c("freq1", "freq2", "freq3" ),
  valeur = c(44, 78, 84)
)

ggplotly(
  ggplot(tbl) +
    geom_bar(aes(x = indicateur, y = valeur), stat = 'identity', fill = rgb(31, 119, 180, maxColorValue = 255)) +
    geom_text(aes(x = indicateur, y = valeur, label = valeur), vjust = -0.5) + 
    ylim(0, max(tbl$valeur)*1.1) +
    labs(x = "", y = "", title = "simple counting") +
    theme_bw() +
    theme(
      axis.line = element_blank(), 
      panel.border = element_blank(),
      plot.title = element_text(hjust = 0.5)
    )
  ) %>%
  layout(
    showlegend = FALSE, 
    textfont = list(size = 5), 
    titlefont = list(size = 12),
    xaxis = list(tickfont = list(size = 9))
  )

提前感谢您的帮助。

【问题讨论】:

    标签: r plotly ggplotly


    【解决方案1】:

    size 传递给geom_text 怎么样?另外,我不认为所有的布局调整都是必要的。请参阅以下内容:

    library(tidyverse)
    library(plotly)
    
    tbl <- data.frame(
      indicateur = c("freq1", "freq2", "freq3" ),
      valeur = c(44, 78, 84)
    )
    
    p_size_5 <- ggplot(tbl, aes(x = indicateur, y = valeur, label = valeur)) +
      geom_bar(stat = "identity", fill = rgb(31, 119, 180, maxColorValue = 255)) +
      geom_text(vjust = -0.5, size = 5) +
      labs(
        title = "simple counting (text 5)",
        x = NULL, y = NULL
      ) +
      theme_bw() +
      theme(
        axis.line = element_blank(),
        panel.border = element_blank(),
        plot.title = element_text(hjust = 0.5)
      )
    
    ggplotly(p_size_5)
    

    p_size_2 <- ggplot(tbl, aes(x = indicateur, y = valeur, label = valeur)) +
      geom_bar(stat = "identity", fill = rgb(31, 119, 180, maxColorValue = 255)) +
      geom_text(vjust = -0.5, size = 2) +
      labs(
        title = "simple counting (text 2)",
        x = NULL, y = NULL
      ) +
      theme_bw() +
      theme(
        axis.line = element_blank(),
        panel.border = element_blank(),
        plot.title = element_text(hjust = 0.5)
      )
    
    ggplotly(p_size_2)
    

    【讨论】:

    • 谢谢!我完全忘记了可以直接从ggplot中将一些值传递给plotly!好吧,我需要那些额外的布局选项,因为我的实际轴标签很长,为了让它们清晰易读,我需要更小的字体。
    猜你喜欢
    • 2017-12-24
    • 2011-07-18
    • 2012-10-14
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多