我试图叠加两个图,一个条形图和一个散点图,它们共享一个 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()
最佳答案
我不确定是什么问题,我认为是与数据量或其他一些与数据相关的问题有关,但是由于您可以单独绘制数据,因此可以为每个图生成一个图像,然后混合两个图像以获得所需的图。
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([])
请记住在两个图中将双轴设置为相同的范围和刻度,否则,图像会有一些偏移并且数字不会对齐。 希望对你有帮助
关于python - 如何在一个图中叠加多个绘图类型(条形图 + 散点图),共享 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57262939/