首页 > 解决方案 > 如何在ggplot2中将科学格式刻度标签更改为缩写形式

问题描述

ggplot用来制作条形图。我已经使用该scales软件包将科学的“2e5”格式更改为用逗号分隔的完整数字。我一直无法更改轴刻度标签,使值 1,000,000 显示为 1M,而 3,500,000 显示为 3.5M,等等。我该怎么做?

请参阅下面的代码:

# Generate dummy dataframe 
df <- structure(list(month = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
), foo = c(2322636.14889234, 8676432.48522654, 207993.984222412, 
3310791.19816422, 7540729.19022292, 7316447.75252789, 2410026.6979076, 
6202864.60500211, 8700672.56037146, 1334956.53280988, 505991.168320179, 
3106733.97500068)), row.names = c(NA, -12L), class = "data.frame")

# create plot
plot.1 <- ggplot2::ggplot(data = df, aes(x = month, y = foo)) +
  geom_bar(stat = 'identity', fill = 'darkorchid4', width = 0.5) +
  theme_minimal() +
  labs(title = "Monthly foo measurements", x = "Month", 
       y = "Amount of foo" ) +
  scale_y_continuous(labels = scales::comma)

提前致谢!

标签: rggplot2

解决方案


ggplot2::ggplot(data = df, aes(x = month, y = foo)) +
  geom_bar(stat = 'identity', fill = 'darkorchid4', width = 0.5) +
  theme_minimal() +
  labs(title = "Monthly foo measurements", x = "Month", 
       y = "Amount of foo" ) +
  scale_y_continuous(label = scales::unit_format(unit = "M", scale = 1e-6, sep = ""))

推荐阅读