自定义 ggplot2 轴和标签格式

Custom ggplot2 axis and label formatting

我正在尝试绘制看起来信息丰富、清晰整洁的标签。

并提出了一个关于 labelaxis 格式的问题。

例如,我有销售数据,其中包括以欧元计的品牌、类别和支出。当 EUR 的总和很大(数百万或更多)时,标签看起来真的很难阅读并且没有提供信息。

结果x-axisScientific notation,也看起来很不干净

我已经设法以自定义方式设置标签格式:它以千为单位显示欧元。 geom_text(aes(label= paste(round(EUR/1000,0),"€"), y=pos), colour="white") 有没有更简单或自动化的方法?

由于 Scientific notation 看起来真的不清楚,对于轴我尝试使用 scale_y_continuous(formatter = "dollar"),但这似乎不起作用。此外,我无法找到是否还实现了 Eur 而不是美元。我认为最好在thousands中显示y-axis。 有什么解决办法吗?

此外,我附上了可重现的例子:

library(plyr)
library(dplyr)
library(ggplot2)
library(scales)


set.seed(1992)
n=68

Category <- sample(c("Black", "Red", "Blue", "Cyna", "Purple"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:5, n, replace = TRUE, prob = NULL))
EUR <- abs(rnorm(n))*100000

df <- data.frame(Category, Brand, EUR)


df.summary = df %>% group_by(Brand, Category) %>% 
  summarise(EUR = sum(EUR)) %>%   # Within each Brand, sum all values in each Category
  mutate( pos = cumsum(EUR)-0.5*EUR)



ggplot(df.summary, aes(x=reorder(Brand,EUR,function(x)+sum(x)), y=EUR, fill=Category)) +
  geom_bar(stat='identity',  width = .7, colour="black", lwd=0.1) +
  geom_text(aes(label=ifelse(EUR>100,paste(round(EUR/1000,0),"€"),""),
                y=pos), colour="white") +
  coord_flip()+
  labs(y="", x="")

您可以在 dollar_format 中为欧元而不是美元设置前缀:

scale_y_continuous(labels=dollar_format(prefix="€")) +

这解决了科学记数法问题。

要以千为单位计算所有内容,您可以在创建摘要时除以 1000。为了减少混乱,您可以在条形标签中省略欧元符号,但我在下面的示例中保留了该符号:

df.summary = df %>% group_by(Brand, Category) %>% 
  summarise(EUR = sum(EUR)/1000) %>%   # Within each Brand, sum all values in each Category
  mutate( pos = (cumsum(EUR)-0.5*EUR))

ggplot(df.summary, aes(x=reorder(Brand,EUR,function(x)+sum(x)), y=EUR, fill=Category)) +
  geom_bar(stat='identity',  width = .7, colour="black", lwd=0.1) +
  geom_text(aes(label=ifelse(EUR>100,paste0("€", round(EUR,0)),""),
                y=pos), colour="white") +
  scale_y_continuous(labels=dollar_format(prefix="€")) +
  coord_flip()+
  labs(y="Thousands of €", x="")

@AK47 闪亮的欧元符号存在解析问题。

尝试将其替换为:(\u20AC)

到目前为止,它对我来说效果很好。

这也有效

scale_y_continuous(labels = function(x) paste0(x, "€"))

您可以用任何符号代替 €