我需要将这两个图放在一起,但当我使用条形图(主要)和线形图(次要)时,效果很好。如果我改变代码行中与绘图相关的顺序,它将不起作用
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
flatui1 = ["#0C6514", "#18AB25"]
flatui2 = ["#0E1D56", "#18AB25"]
colors = sns.color_palette(flatui1)
cmap1 = LinearSegmentedColormap.from_list("my_colormap", colors)
colors = sns.color_palette(flatui2)
cmap2 = LinearSegmentedColormap.from_list("my_colormap", colors)
sns.set_style(style='whitegrid')
m1_t = pd.DataFrame({
"A":[0.21,0.05,1.22,0.41,1.28,1.15,0.91,0.63,0.38,1.18],
"B":[13.33,18,23.69,21.46,35.31,16,20.11,15.87,20.53,17.71],
"C":[5.71,2,23.44,9.02,35.39,13.48,14.62,13.17,13.68,14.66]
})
# This two line sequence has the problem
m1_t['A'].plot(kind='bar',colormap=cmap1)
m1_t[['B','C']].plot(kind='line',secondary_y=True,colormap=cmap2)
ax = plt.gca()
ax.grid(True)
ax.set_axisbelow(True)
ax.set_xticklabels(('P0', 'P1','P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9'))
plt.savefig('Comparison',dpi=300)
plt.show()
绘制此图的更好方法是使用面向对象的matplotlib api。首先我们必须定义
Figure
和axes
,然后为了正确地绘制第二个y,我们将创建一个伪轴对象,该对象链接回我们创建的原始轴。然后我们可以告诉熊猫直接在我们的坐标轴上绘图,以确保一切都在正确的位置无论代码行的顺序如何,这个解决方案都会起作用,因为我们告诉熊猫在特定轴上绘图,而不是让它选择在一组现有轴上绘图或创建一个新轴
编辑:
手动指定zorder是控制元素绘制顺序的可靠方法。本质上,具有较高zorder的元素将位于具有较低zorder的元素之上。在本例中,网格的zorder为0,条形图和线条的zorder为1和2,确保它们位于网格顶部(因为它们的zorder高于0)
编辑2(添加图例):
以下两轴图的方法很简单,因为它保留索引并包含图例
相关问题 更多 >
编程相关推荐