簡體   English   中英

用 ggplot 繪制負直方圖

[英]Plot negative histogram with ggplot

我從同一個數據框中繪制了兩個系列。 其中之一具有負值。

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 軸上。

你可以試試這個。 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..))) 

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM