【问题标题】:Plotting data with a string as the x-axis以字符串为 x 轴绘制数据
【发布时间】:2017-02-02 14:14:34
【问题描述】:

我在 pandas 数据框中有以下数据集,在 x 轴上绘制 timeOfDay 和在 y 轴上绘制 Wattage 时遇到问题。基本上,我正在尝试制作散点图(plt.scatter),x 轴带有3 点(早上、下午、晚上),它们各自的WattagestimeOfDay 上方。

因此,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

【问题讨论】:

  • 也许可以将MorningAfternoonEvening分别转换为0、1和2。然后将这些数字绘制为 X,将瓦数绘制为 Y

标签: python matplotlib scatter-plot


【解决方案1】:

您可以使用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()

【讨论】:

    【解决方案2】:

    如果您已经有一个包含数据的数据框,则可以轻松使用seaborn swarmplot,这使它成为单行:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      相关资源
      最近更新 更多