Pandas在一个轴上绘制的紧凑图。

huangapple go评论85阅读模式
英文:

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()

结果:

Pandas在一个轴上绘制的紧凑图。

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

英文:

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[&#39;x&#39;] = np.linspace(20, 30, 10)
df[&#39;y&#39;] = np.random.randint(1, 10, 10)

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

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

plt.show()

<b>Result:</b>

Pandas在一个轴上绘制的紧凑图。

<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')

Pandas在一个轴上绘制的紧凑图。

英文:

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[&#39;x&#39;] = np.linspace(20, 30, 10)
df[&#39;y&#39;] = np.random.randint(1, 10, 10)

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

fig, ax = plt.subplots()

ax.bar(x=df.x, height=df.y)
ax.plot(df2.set_index(&#39;x&#39;), c=&#39;red&#39;)

Pandas在一个轴上绘制的紧凑图。

huangapple
  • 本文由 发表于 2020年1月3日 19:04:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577455.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定