【发布时间】:2019-01-27 04:35:02
【问题描述】:
假设我有下面的数据框:
import pandas as pd
data = {'Col1':['(-2.0, 1.0]', '(1.0, 4.0]', '(4.0, 6.0]', '(6.0, 9.0]', '(9.0, 11.0]', '(11.0, 14.0]', '(14.0, 16.0]', '(16.0, 19.0]', '(19.0, 21.0]', '(21.0, 24.0]'],
'Col2':[3.409836, 2.930693, 2.75, 3.140845, 2.971429, 2.592593, 2.6, 3.1875, 2.857143, 0.714286]}
df = pd.DataFrame(data, columns=['Col1', 'Col2'])
df
我想针对df.Col1 绘制df.Col2。但由于Col1 包含范围或箱,Col1 值不是浮点数或整数 - 它们是字符串。因此,该图没有按顺序显示 x 轴:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,5))
plt.plot([str(i) for i in df.Col2], df.Col1)
我该如何解决这个问题?
编辑:对于多个子图我不能使用df.plot(x='Col1',y='Col2'),因为我将此图作为子图之一:
df1 = pd.DataFrame(data, columns=['Col1', 'Col2'])
df2 = df1
df3 = df1
fig = plt.figure(figsize=(20,5))
plt.subplot(1,3,1)
plt.plot([str(i) for i in df1.Col1], df1.Col2)
plt.subplot(1,3,2)
plt.plot([str(i) for i in df2.Col1], df2.Col2)
plt.subplot(1,3,3)
plt.plot([str(i) for i in df3.Col1], df3.Col2)
我尝试了以下方法:
fig, axes = plt.subplots(nrows=1, ncols=3)
plt.subplot(1,3,1)
df1.plot(x='Col1',y='Col2',ax=axes[0,0])
plt.subplot(1,3,2)
df2.plot(x='Col1',y='Col2',ax=axes[0,1])
plt.subplot(1,3,3)
df3.plot(x='Col1',y='Col2',ax=axes[0,2])
但是得到了这个错误:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-113-b0fcf5cd6711> in <module>()
2
3 plt.subplot(1,3,1)
----> 4 df1.plot(x='Col1',y='Col2',ax=axes[0,0])
5
6 plt.subplot(1,3,2)
IndexError: too many indices for array
我也得到了完全相同的错误:
fig, axes = plt.subplots(nrows=1, ncols=3)
df1.plot(x='Col1',y='Col2',ax=axes[0,0])
df2.plot(x='Col1',y='Col2',ax=axes[0,1])
df3.plot(x='Col1',y='Col2',ax=axes[0,2])
编辑 2: 好的,我遇到了this 答案的第一条评论,以下是有效的:
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(20,5))
df1.plot(x='Col1',y='Col2',ax=axes[0])
df2.plot(x='Col1',y='Col2',ax=axes[1])
df3.plot(x='Col1',y='Col2',ax=axes[2])
编辑 3:用于在一个图中绘制 3 个数据框
ax = df1.plot(x='Col1',y='Col2')
df2.plot(x='Col1',y='Col2',ax=ax)
df3.plot(x='Col1',y='Col2',ax=ax)
【问题讨论】:
-
@Kristada673 是预期的情节:This plot
-
@U9-Forward 是的,这是预期的图,x 轴点按顺序排列。
-
@Kristada673 好的,很好
-
@Kristada673 你说的顺序是什么意思?
-
您只需
df.plot(x='Col1',y='Col2')。它将按顺序绘制
标签: python pandas matplotlib plot graph