第二个Y轴,带有其他比例 [英] second y-axis with other scale

查看:50
本文介绍了第二个Y轴,带有其他比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用ggplot2 geom_bar创建了一个条形图,希望在条形图中有两个指标.我用融化来做.但是,我现在需要另一个带有另一个刻度的y轴,因为这两个指标的数量差异太大.

I created a barchart with ggplot2 geom_bar and want to have two metrics in the bars. I used melt to do so. However, I now need a second y-axis with another scale, because the numbers of the two metrics are too different.

在下面的数据框和我使用的代码中:

In the following the dataframe and the code I used:

df <- data.frame(categories = c("politics", "local", "economy", "cultural events", 
                                "politics", "local", "economy", "cultural events"), 
               metric = c("page", "page", "page", "page", 
                          "product", "product", "product", "product"), 
               value = c(100L, 50L, 20L, 19L, 
                         950000L, 470000L, 50000L, 1320L))

在下面的代码中,我用于创建绘图和第二个y轴:

In the following the code I used to create the plot and the second y-axis:

x <- ggplot(df, aes(x=categories, y=value, fill = metric))
x + geom_bar(stat = "identity", position = "dodge") +
  scale_y_continuous(sec.axis=sec_axis(~. *1000), limits=c(1,1000))

但是,现在图表中不再显示任何条形...有人知道如何解决此问题吗?

However, now no bars appear in the chart anymore... Does anybody know how to solve this problem?

推荐答案

另一种方法可能是使用 highcharter

Another approach could be to use highcharter

library(dplyr)
library(tidyr)
library(highcharter)

#convert your data in wide format
df <- df %>% spread(metric, value)

#plot
highchart() %>% 
  hc_xAxis(categories = df$categories) %>%
  hc_yAxis_multiples(
    list(lineWidth = 3, title = list(text = "Page")),
    list(opposite = TRUE, title = list(text = "Product"))
  ) %>% 
  hc_add_series(type = "column", data = df$page) %>% 
  hc_add_series(type = "line", data = df$product, yAxis=1) # replace "line" with "column" to have it in bar format

输出图为:

样本数据:

df <- structure(list(categories = structure(c(4L, 3L, 2L, 1L, 4L, 3L, 
2L, 1L), .Label = c("cultural events", "economy", "local", "politics"
), class = "factor"), metric = structure(c(1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L), .Label = c("page", "product"), class = "factor"), 
    value = c(100L, 50L, 20L, 19L, 950000L, 470000L, 50000L, 
    1320L)), .Names = c("categories", "metric", "value"), row.names = c(NA, 
-8L), class = "data.frame")

这篇关于第二个Y轴,带有其他比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆