用GGPLOT绘制负面直方图

发布于 2025-02-12 20:09:07 字数 538 浏览 2 评论 0原文

我从同一数据框架中绘制两个系列。其中一个具有负值。

p_change <- ggplot(dx, aes(fill=Group)) +
  geom_histogram(aes(x=posvalues), binwidth=1) +
  geom_histogram(aes(x=negvalues), binwidth=1) +
  xlim(0, 15) +
  ylim(-25, 25) +
  xlab('Number of tokens') +
  theme(
    legend.position = "right",
    text=element_text(size = 19)
  )
p_change

我希望将第二个直方图绘制在负y轴上。

I plot two series from the same dataframe. One of them has negative values.

p_change <- ggplot(dx, aes(fill=Group)) +
  geom_histogram(aes(x=posvalues), binwidth=1) +
  geom_histogram(aes(x=negvalues), binwidth=1) +
  xlim(0, 15) +
  ylim(-25, 25) +
  xlab('Number of tokens') +
  theme(
    legend.position = "right",
    text=element_text(size = 19)
  )
p_change

enter image description here

I would like the second histogram to be plotted on the negative y-axis.

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

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

发布评论

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

评论(1

烟沫凡尘 2025-02-19 20:09:07

您可以尝试这个。 IMO更有意义地将负值绘制在Xaxis上。

library(tidyverse)

# some data in the long format (recommended format for ggplot)
data <- mtcars %>% 
  mutate(negdisp=-disp) %>% 
  select(contains("disp")) %>% 
  pivot_longer(everything()) 

data
# A tibble: 64 x 2
   name    value
   <chr>   <dbl>
 1 disp      160
 2 negdisp  -160
 3 disp      160
 4 negdisp  -160

  data %>% 
  ggplot(aes(value, fill = name)) + 
   geom_histogram() 

类的东西来完成使用Yaxis的解决方案

data %>% 
  ggplot(aes(x = abs(value), fill = name)) + 
  stat_bin(aes(y=ifelse(fill == "negdisp", -..count.., ..count..))) 

可以使用

You can try this one. IMO it makes more sense that the negative values are plotted on the xaxis.

library(tidyverse)

# some data in the long format (recommended format for ggplot)
data <- mtcars %>% 
  mutate(negdisp=-disp) %>% 
  select(contains("disp")) %>% 
  pivot_longer(everything()) 

data
# A tibble: 64 x 2
   name    value
   <chr>   <dbl>
 1 disp      160
 2 negdisp  -160
 3 disp      160
 4 negdisp  -160

  data %>% 
  ggplot(aes(value, fill = name)) + 
   geom_histogram() 

enter image description here

The solution with the yaxis can be done using something like

data %>% 
  ggplot(aes(x = abs(value), fill = name)) + 
  stat_bin(aes(y=ifelse(fill == "negdisp", -..count.., ..count..))) 

enter image description here

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