簡體   English   中英

如何在一個圖中疊加多個繪圖類型(條形+散點圖),共享x軸

[英]How do I overlay multiple plot types (bar + scatter) in one figure, sharing x-axis

我試圖疊加兩個圖形,一個條形圖和一個散點圖,它們共享一個x軸,但在圖形的兩邊都有單獨的y軸。 我嘗試過使用matplotlib,ggplot和seaborn,但我遇到了同樣的問題。 我可以單獨繪制它們,並且它們正確地繪制圖形,但是當我嘗試將它們一起繪制時,條形圖是正確的,但是,只有散點圖中的幾個數據點出現。 我已經放大並且可以確認幾乎沒有散點圖出現。

這是我的代碼。 我已經加載了一個pandas數據幀,我試圖將'dKO_Log2FC'圖形化為條形圖,並將'TTCAAG'作為散點圖。 它們都在x軸上共享'bin_end'位置。 如果我注釋掉sns.barplot,散點圖就會完美地顯示出來。 如果我注釋掉sns.scatterplot,那么條形圖也是如此。 當我將它們一起繪制而沒有注釋掉時,條形圖圖形,但只有兩個來自“TTCAAG”列的數據點出現。 我玩散射點的大小,放大等等,但沒有任何效果。

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd

file = pd.read_csv('path/to/csv_file.csv')
df = pd.DataFrame(file, columns=['bin_end', 'TTCAAG', 'dKO_Log2FC'])

bin_end = df['bin_end']
TTCAAG = df['TTCAAG']
dKO_Log2FC = df['dKO_Log2FC']

fig, ax = plt.subplots()
ax2 = ax.twinx()

sns.barplot(x=bin_end, y=dKO_Log2FC, ax=ax, color="blue", data=df)

sns.scatterplot(x=bin_end, y=TTCAAG, ax=ax2, color="red", data=df)

plt.title('Histone Position in TS559 vs dKO')
plt.xlabel('Genomic Position (Bin = 1000nt)', fontsize=10)
plt.xticks([])
plt.ylabel('Log2 Fold Change', fontsize=10)

plt.show()

我不知道為什么這個散點圖不能完全繪制圖形。 數據集非常大,但即使我將其分解為較小的位,也只會顯示幾個散點。 這是圖表 分散 酒吧 bar + scatter

我不確定是什么問題,我認為是與數據量或其他一些數據相關的問題,但是你可以單獨繪制數據,你可以為每個繪圖生成一個圖像然后混合這兩個圖像獲得所需的情節。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from PIL import Image

npoints=200
xRange=np.arange(0,npoints,1)
randomdata0=np.abs(np.random.normal(0,1,npoints))
randomdata1=np.random.normal(10,1,npoints)
axtick=[7,10,14]
ax2tick=[0,1.5,3]

fig0=plt.figure(0)
ax=fig0.gca()
ax2=ax.twinx()
sns.scatterplot(x=xRange,y=randomdata1,ax=ax)
ax.set_yticks(axtick)
ax.set_ylim([6,15])
ax2.set_yticks(ax2tick)
ax2.set_ylim([0,3.5])
plt.xticks([])

canvas0 = FigureCanvas(fig0)
s, (width, height) = canvas0.print_to_buffer()
X0 = Image.frombytes("RGBA", (width, height), s) #Contains the data of the first plot

在此輸入圖像描述

fig1=plt.figure(1)
ax=fig1.gca()
ax2=ax.twinx()
sns.barplot(x=xRange,y=randomdata0,ax=ax2)
ax.set_yticks(axtick)
ax.set_ylim([6,15])
ax2.set_yticks(ax2tick)
ax2.set_ylim([0,3.5])
plt.xticks([])

canvas1 = FigureCanvas(fig1)
s, (width, height) = canvas1.print_to_buffer()
X1 = Image.frombytes("RGBA", (width, height), s) #Contains the data of the second plot

在此輸入圖像描述

plt.figure(13,figsize=(10,10))
plt.imshow(Image.blend(X0,X1,0.5),interpolation='gaussian')
Axes=plt.gca()
Axes.spines['top'].set_visible(False)
Axes.spines['right'].set_visible(False)
Axes.spines['bottom'].set_visible(False)
Axes.spines['left'].set_visible(False)
Axes.set_xticks([])
Axes.set_yticks([])

在此輸入圖像描述

只記得設置兩個相同范圍的雙軸並在兩個圖中打勾,否則,圖像中會有一些偏移,數字將不對齊。 希望能幫助到你

暫無
暫無

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

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