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

was following example并提出了另一个有关labelaxis格式的问题。

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

结果,x-axisScientific notation中,并且看起来也很不整洁。

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

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

另外,我附上可复制的示例:

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


r - 自定义ggplot2轴和标签格式-LMLPHP

最佳答案

您可以在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="")


r - 自定义ggplot2轴和标签格式-LMLPHP

07-24 09:52
查看更多