【问题标题】:Custom ggplot2 axis and label formatting自定义 ggplot2 轴和标签格式
【发布时间】:2016-10-06 08:06:55
【问题描述】:

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

was following example 又提出了一个关于labelaxis 格式的问题。

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

结果,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="")

【问题讨论】:

    标签: r ggplot2 axis labels axis-labels


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这也有效

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

      你可以用任何你想要的符号代替€

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多