简体   繁体   English

如何统一ggplot中的小数位数?

[英]How can I unify the number of decimal places in ggplot?

I have a more complex code compared to the examples provided and cannot imagine how I have to change the code to obtain the same number of decimal places for all bars of my bar chart. 与提供的示例相比,我有一个更复杂的代码,无法想象我如何更改代码以获得条形图所有条形图的相同小数位数。 For most of the bars, R already shows two decimal places. 对于大多数条形,R已经显示两个小数位。 Whenever the second decimal place is a "0", however, R only shows one decimal place. 但是,每当小数点后两位为“0”时,R只显示一个小数位。 Can someone please show me how to standardize the decimal place to 2 and how to integrate the command in my code? 有人可以告诉我如何将小数位标准化为2以及如何在我的代码中集成命令?

I already tried "digits" and specify_decimal but failed to correctly integrate it into my code (in scale_x_continuous). 我已经尝试了“digits”和specify_decimal但未能将它正确地集成到我的代码中(在scale_x_continuous中)。

df1_long %.>%
  ggplot(
    data = .,
    aes(
      x = xpos,
      y = val,
      fill = Ebene
  )) +
  geom_rect(aes(
      xmin = xpos - .5,
      xmax = xpos + .5,
      ymin = -Inf,
      ymax = Inf,
      fill = Problemzahl
    ),
    alpha = .3
  ) +
  geom_col(
    position = position_dodge(.5),
    colour="black",
    width = .5
  ) +
  geom_errorbar(aes(
      ymin = val - SE,
      ymax = val + SE
    ),
    position = position_dodge(.5),
    width = .2
  ) +
  geom_text(aes(
      y = val + SE + .02,
      label = val %>% str_replace('\\.', ',')
    ),
    position = position_dodge(.5)
  ) +
  scale_fill_manual(
    values = c(
      '#aaaaaa',  # Beide Problemarten
      '#000000',  # Co
      '#dddddd',  # Keine Probleme
      '#CCCCCC',  # Motivationale Probleme
      '#333333',  # Self
      '#666666',  # Shared
      '#bbbbbb'   # Verständnisbezogene Probleme  
    ),
    breaks = c(
      'Self',
      'Co',
      'Shared'
    )
  ) +
  scale_x_continuous(
    breaks = .$xpos %>% unique(),
    labels = .$Problemzahl %>% unique(),
    expand = c(0, 0)
  ) +
  scale_y_continuous(
    labels = function(x) str_replace(x, '\\.', ','),
    limits = c(0, 1.0),
    expand = c(0, 0)
  ) +
  ylab('Allgemeine Regulationsaktivität auf der Self-, Co-, und Shared Ebene\n(KI 95%)') +
  theme_classic() +
  theme(
    legend.position = 'top',
    legend.title = element_blank(),
    legend.spacing.x = unit(1, 'mm'),
    axis.title.x = element_blank()
  )

I would alter the code in your pipe before calling ggplot. 在调用ggplot之前,我会更改管道中的代码。 Here's a nice example using the formattable package. 这是使用formattable包的一个很好的例子。

library(tidyverse)
library(formattable)

df1_long %>%
  mutate(val = formattable(val, digits = 2, format = "f")) %>%
  ggplot(
  ...
)

You can substitute whatever variable name for val, depending on which one you want to standardize to two decimal places. 您可以将任何变量名称替换为val,具体取决于您要标准化为两个小数位的变量名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM