Matplotlib:将多列绘制到具有不同y轴的图形中

时间:2018-11-07 23:41:39

标签: python matplotlib plot

我想绘制一个与此相似的图形(对不起,它看起来不太好):

enter image description here

像这样说有数据:

ExecutorChannel

有人知道怎么做吗?谢谢,我尝试挖掘堆栈溢出,但未发现任何类似的问题。 谢谢您的任何想法和建议!

2 个答案:

答案 0 :(得分:0)

您在寻找这个吗?

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

y = np.random.rand(10,3)
y[:,0]= np.arange(1,11)
df = pd.DataFrame(y, columns=['x', 'v', 't'])

fig = plt.figure() # Create matplotlib figure

ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.

width = 0.4

df.plot(x='x',y='v',kind='bar', color='red', ax=ax, width=width, position=1)
df.t.plot(x='x', y='t[::-1]',kind='bar', color='blue', ax=ax2, width=width, position=0)

ax.set_ylabel('v')
ax2.set_ylabel('t')


plt.show()

答案 1 :(得分:0)

这是我的解决方案。实际上,这非常简单,使用ax2 = ax.twinx()之后,将ax2 y轴的范围翻转ax2.set_ylim(BIG_NUMBER,SMALL_NUMBER)

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

y = np.random.rand(10,3)
y[:,0]= np.arange(1,11)
df = pd.DataFrame(y, columns=['x', 'v', 't'])
df['x'] = np.arange(1, 11, 1)

fig = plt.figure() # Create matplotlib figure

ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.


ax.bar(df['x'],df['v'], color='red', alpha=0.8)
ax.set_ylabel('v', color='red')
ax.tick_params(axis='y', labelcolor='red')
ax.set_ylim(0, 1.5)

ax2.bar(df['x'], df['t'], color='blue', alpha=0.5)
ax2.set_ylabel('t', color='b')
ax2.tick_params(axis='y', labelcolor='blue')
ax2.set_ylim(1.5, 0)

plt.show()