如何在同一图中绘制熊猫数据框而又不破坏它们的实际方向?

时间:2018-11-06 15:20:06

标签: python pandas dataframe matplotlib twinx

我试图比较朴素矩阵乘法 Strassen的之间的运行时间。为此,我记录了矩阵不同维度的运行时。然后,我试图将结果绘制在同一张图中以进行比较。

但是问题是绘图没有显示正确的结果。

  1. 这是数据... 2 3142 3 3531 4 4756 5 5781 6 8107

最左边的列表示n,维度和最右边的列表示执行时间。

以上数据适用于天真的方法,而 Strassen 的数据也属于这种模式。

我正在将此数据插入熊猫数据框。在绘制数据后,图像如下所示: enter image description here

此处蓝色表示天真,绿色表示 Strassen的 这肯定是不正确的,因为天真不能保持不变。但是我的代码是正确的。所以我决定分别绘制它们,结果如下:

天真 Naive

Strassen enter image description here

如您所见,可能会发生,因为Y轴的缩放比例不一样吗? 是这个原因吗?

我正在实现的绘图代码是:

fig = plt.figure()

data_naive = pd.read_csv('naive.txt', sep="\t", header=None)
data_naive.columns = ["n", "time"]
plt.plot(data_naive['n'], data_naive['time'], 'g')

data_strassen = pd.read_csv('strassen.txt', sep="\t", header=None)
data_strassen.columns = ["n", "time"]
plt.plot(data_strassen['n'], data_strassen['time'], 'b')

plt.show()

fig.savefig('figure.png')

我试图解决的问题?

fig = plt.figure()

data_naive = pd.read_csv('naive.txt', sep="\t", header=None)
data_naive.columns = ["n", "time"]

data_strassen = pd.read_csv('strassen.txt', sep="\t", header=None)
data_strassen.columns = ["n", "time"]

ax = data_naive.plot(x='n', y='time', c='blue', figsize=(20,10))
data_strassen.plot(x='n', y='time', c='green', figsize=(20,10), ax=ax)

plt.savefig('comparison.png')
plt.show()

但是没有运气!!!

如何在不改变其实际方向的情况下将它们绘制在同一图中?

1 个答案:

答案 0 :(得分:-1)

IIUC:这是使用twinx

的解决方案
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randint(10, 100, (12,2)))
df[1] = np.random.dirichlet(np.ones(12)*1000., size=1)[0]

fig, ax1 = plt.subplots()
ax1.plot(df[0], color='r')
#Plot the secondary axis in the right side
ax2 = ax1.twinx()
ax2.plot(df[1], color='k')
fig.tight_layout()
plt.show()

产生的结果: enter image description here