功能sec.axis不显示第二个变量的条形

发布于 2025-02-12 09:06:54 字数 657 浏览 1 评论 0原文

我必须计算一个带有2个bar的图,每个X观测值。 Y1是一个可以假设大量值的变量(也数十万) Y2在[0,100]范围内。 我报告了一个有虚拟数据的示例。 问题是Y1还可以,但是参考第一个轴值而不是第二个轴(因此,Y2是看不见的)。

library(tidyverse)

data = data.frame("x" = c("A", "B", "C", "D", "E", "F", "G", "H"), 
                  "y1" = c(10000, 70000, 120000, 75000, 500, 2000, 10000, 18000),
                  "y2" = c(22, 30, 36, 10, 1, 80, 33, 39))

data %>%
  gather("Type", "Value", -x) %>%
  ggplot(aes(x, Value, fill = Type))+
  geom_bar(position = "dodge", stat = "identity")+
  scale_y_continuous(name = "First axis",
                     sec.axis = sec_axis(~./1000, name = "Second axis"))

此外,将Y2轴限制为100是很好的。

I have to compute a plot with 2 bars for each x observation.
y1 is a variable that can assume large values (also hundreds of thousands)
y2 is in the range [0, 100].
I have reported an example with fictitious data.
The problem is that y1 is okay, but y2 is plotted with reference to the first axis values instead of the second one (and so it's pratically invisible).

library(tidyverse)

data = data.frame("x" = c("A", "B", "C", "D", "E", "F", "G", "H"), 
                  "y1" = c(10000, 70000, 120000, 75000, 500, 2000, 10000, 18000),
                  "y2" = c(22, 30, 36, 10, 1, 80, 33, 39))

data %>%
  gather("Type", "Value", -x) %>%
  ggplot(aes(x, Value, fill = Type))+
  geom_bar(position = "dodge", stat = "identity")+
  scale_y_continuous(name = "First axis",
                     sec.axis = sec_axis(~./1000, name = "Second axis"))

Moreover, it would be good limiting the y2 axis to 100.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

遥远的绿洲 2025-02-19 09:06:54

只需在sec_axis中应用转换就不够。您还必须重新列出我添加突变步骤的数据。要获得辅助轴的最大范围,您必须调整缩放率,即您的示例数据1250工作。

library(tidyverse)

data %>%
  mutate(y2 = y2 * 1250) %>%
  gather("Type", "Value", -x) %>%
  ggplot(aes(x, Value, fill = Type)) +
  geom_bar(position = "dodge", stat = "identity") +
  scale_y_continuous(
    name = "First axis",
    sec.axis = sec_axis(~ . / 1250, name = "Second axis")
  )

“”

Simply applying a transformation in sec_axis isn't sufficient. You also have to rescale the data for which I added a mutate step. To get a max range for the secondary axis you have to adjust the scaling, i.e. for your example data 1250 works.

library(tidyverse)

data %>%
  mutate(y2 = y2 * 1250) %>%
  gather("Type", "Value", -x) %>%
  ggplot(aes(x, Value, fill = Type)) +
  geom_bar(position = "dodge", stat = "identity") +
  scale_y_continuous(
    name = "First axis",
    sec.axis = sec_axis(~ . / 1250, name = "Second axis")
  )

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文