【问题标题】:Pandas squished plot on one axis熊猫在一个轴上压扁地块
【发布时间】:2020-04-21 22:50:28
【问题描述】:

我有两个数据框,我需要在一个轴上绘制。不幸的是,显示的数据和 xticks 之一向左移动。

测试示例:

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

df = pd.DataFrame()
df['x'] = np.linspace(20, 30, 10)
df['y'] = np.random.randint(1, 10, 10)

df2 = pd.DataFrame()
df2['x'] = np.linspace(1, 40, 50)
df2['y'] = np.random.randint(1, 10, 50)

fig, ax = plt.subplots()
df.plot(x='x', y='y', kind='bar', ax=ax, width=1., figsize=(3, 2.5), legend=None)
df2.plot(x='x', y='y', kind='line', ax=ax, legend=None, color='red')

plt.show()

结果:

问题: 如何在一个轴上正确显示这些数据?

【问题讨论】:

标签: python pandas matplotlib


【解决方案1】:

我只能通过直接在 matplotlib 中绘图来解决这个问题:

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

df = pd.DataFrame()
df['x'] = np.linspace(20, 30, 10)
df['y'] = np.random.randint(1, 10, 10)

df2 = pd.DataFrame()
df2['x'] = np.linspace(1, 40, 50)
df2['y'] = np.random.randint(1, 10, 50)

fig, ax = plt.subplots()

ax.bar(x=df.x, height=df.y)
ax.plot(df2.set_index('x'), c='red')

【讨论】:

  • Pandas 条形图是分类的(它们总是从 0 到 N-1),而 matplotlib 条形图是数字的。因此,这不是错误,而是条形图解释的不同方式。
  • @ImportanceOfBeingErnest 好的,感谢您的解释(以及您在本网站上所做的所有其他出色工作)!
猜你喜欢
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 2022-06-12
  • 2019-08-30
  • 2018-01-22
  • 2018-10-25
  • 2014-04-27
  • 1970-01-01
相关资源
最近更新 更多