自定义ggplot2轴和标签格式

AK4*_*K47 11 axis r labels ggplot2 axis-labels

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

是下面的例子,并提出一个问题关于labelaxis格式.

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

结果,x-axis是,Scientific notation并且看起来也非常不洁净.

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

由于Scientific notation看起来真的不清楚,对于轴我尝试使用scale_y_continuous(formatter = "dollar"),但这似乎不工作.而且,我无法找到是否Eur还实施而不是美元.我相信,这将是最好的展现y-axisthousands.有解决方案吗

另外,我附上可重复的例子:

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="")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

eip*_*i10 14

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

scale_y_continuous(labels=dollar_format(prefix="€")) +
Run Code Online (Sandbox Code Playgroud)

这照顾了科学记数法问题.

要获得成千上万的所有内容,您可以在创建摘要时除以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="")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


小智 5

这也有效

\n\n
scale_y_continuous(labels = function(x) paste0(x, "\xe2\x82\xac"))\n
Run Code Online (Sandbox Code Playgroud)\n\n

您可以放置​​任何您想要的符号来代替 \xe2\x82\xac

\n