英文:
Pandas squished plot on one axis
问题
我有两个数据框需要在同一坐标轴上绘制。不幸的是,其中一个显示的数据和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()
结果:
问题:
如何在一个坐标轴上正确显示这些数据?
英文:
I have two data frames with i need to plot in one axis. Unfortunately one of displayed data and xticks are shifted to the left.
<b>Test example:</b>
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()
<b>Result:</b>
<b>Question:</b>
How to proper display this data on one axis?
答案1
得分: 3
我只能通过在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')
英文:
I was only able to solve this by doing the plot in matplotlib directly:
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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论