如何在ggplot2中将科学格式刻度标签更改为缩写形式

时间:2019-01-03 10:21:08

标签: r 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)

谢谢!

1 个答案:

答案 0 :(得分:3)

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 = ""))