以字符串作为 x 轴绘制数据
Plotting data with a string as the x-axis
我在下面的 pandas 数据框中有以下数据集,我无法在 x 轴上绘制 timeOfDay
,在 y 轴上绘制 Wattage
.基本上,我试图制作一个散点图 (plt.scatter
),x 轴带有 3
个点(早上、下午、晚上),并且它们各自的 Wattages
在 timeOfDay
.
因此,Morning
的三个数据点位于其上方,Afternoon
的数据点位于其上方,依此类推。
Wattage time_stamp timeOfDay
0 100 2015-02-24 10:00:00 Morning
1 120 2015-02-24 11:00:00 Morning
2 104 2015-02-24 12:00:00 Morning
3 105 2015-02-24 13:00:00 Afternoon
4 109 2015-02-24 14:00:00 Afternoon
5 120 2015-02-24 15:00:00 Afternoon
6 450 2015-02-24 16:00:00 Afternoon
7 200 2015-02-24 17:00:00 Evening
8 300 2015-02-24 18:00:00 Evening
9 190 2015-02-24 19:00:00 Evening
10 100 2015-02-24 20:00:00 Evening
11 110 2015-02-24 21:00:00 Evening
您可以使用xticks方法:
import numpy as np
import matplotlib.pyplot as plt
y = np.array( [100, 120, 104, 105, 109, 120, 450, 200, 300, 190, 100, 110] )
x = []
labels = [ 'Morning', 'Morning','Morning','Afternoon','Afternoon','Afternoon','Afternoon', 'Evening', 'Evening', 'Evening', 'Evening', 'Evening']
for q in labels:
if q == 'Morning':
x.append(0)
elif q == 'Afternoon':
x.append(1)
elif q == 'Evening':
x.append(2)
plt.scatter(x, y)
plt.xticks( x, labels )
plt.show()
如果您已经有了包含数据的数据框,您可以轻松使用 seaborn swarmplot,这使得它成为 one-liner:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
w = [100,123,156,90,40,320,198,174,175,146,238,120]
m = ["morning"]*4+ ["noon"]*4+["evening"]*4
df = pd.DataFrame({"Wattage" : w, "timeOfDay":m})
sns.swarmplot(x="timeOfDay", y="Wattage", data=df)
plt.show()
我在下面的 pandas 数据框中有以下数据集,我无法在 x 轴上绘制 timeOfDay
,在 y 轴上绘制 Wattage
.基本上,我试图制作一个散点图 (plt.scatter
),x 轴带有 3
个点(早上、下午、晚上),并且它们各自的 Wattages
在 timeOfDay
.
因此,Morning
的三个数据点位于其上方,Afternoon
的数据点位于其上方,依此类推。
Wattage time_stamp timeOfDay
0 100 2015-02-24 10:00:00 Morning
1 120 2015-02-24 11:00:00 Morning
2 104 2015-02-24 12:00:00 Morning
3 105 2015-02-24 13:00:00 Afternoon
4 109 2015-02-24 14:00:00 Afternoon
5 120 2015-02-24 15:00:00 Afternoon
6 450 2015-02-24 16:00:00 Afternoon
7 200 2015-02-24 17:00:00 Evening
8 300 2015-02-24 18:00:00 Evening
9 190 2015-02-24 19:00:00 Evening
10 100 2015-02-24 20:00:00 Evening
11 110 2015-02-24 21:00:00 Evening
您可以使用xticks方法:
import numpy as np
import matplotlib.pyplot as plt
y = np.array( [100, 120, 104, 105, 109, 120, 450, 200, 300, 190, 100, 110] )
x = []
labels = [ 'Morning', 'Morning','Morning','Afternoon','Afternoon','Afternoon','Afternoon', 'Evening', 'Evening', 'Evening', 'Evening', 'Evening']
for q in labels:
if q == 'Morning':
x.append(0)
elif q == 'Afternoon':
x.append(1)
elif q == 'Evening':
x.append(2)
plt.scatter(x, y)
plt.xticks( x, labels )
plt.show()
如果您已经有了包含数据的数据框,您可以轻松使用 seaborn swarmplot,这使得它成为 one-liner:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
w = [100,123,156,90,40,320,198,174,175,146,238,120]
m = ["morning"]*4+ ["noon"]*4+["evening"]*4
df = pd.DataFrame({"Wattage" : w, "timeOfDay":m})
sns.swarmplot(x="timeOfDay", y="Wattage", data=df)
plt.show()