Draw a plot in which the Y-axis text data (not numeric), and X-axis numeric data

后端 未结 3 1643
说谎
说谎 2021-01-29 09:59

I can create a simple columnar diagram in a matplotlib according to the \'simple\' dictionary:

import matplotlib.pyplot as plt
D = {u\'Label1\':26, u\'Label2\'         


        
3条回答
  •  别那么骄傲
    2021-01-29 10:40

    Use numeric values for your y-axis ticks, and then map them to desired strings with plt.yticks():

    import matplotlib.pyplot as plt
    import pandas as pd 
    
    # example data
    times = pd.date_range(start='2017-10-17 00:00', end='2017-10-17 5:00', freq='H')
    data = np.random.choice([0,1], size=len(times))
    data_labels = ['need1','need2']
    
    fig, ax = plt.subplots()
    ax.plot(times, data, marker='o', linestyle="None")
    plt.yticks(data, data_labels)
    plt.xlabel("time")
    

    Note: It's generally not a good idea to use a line graph to represent categorical changes in time (e.g. from need1 to need2). Doing that gives the visual impression of a continuum between time points, which may not be accurate. Here, I changed the plotting style to points instead of lines. If for some reason you need the lines, just remove linestyle="None" from the call to plt.plot().

    UPDATE
    (per comments)

    To make this work with a y-axis category set of arbitrary length, use ax.set_yticks() and ax.set_yticklabels() to map to y-axis values.

    For example, given a set of potential y-axis values labels, let N be the size of a subset of labels (here we'll set it to 4, but it could be any size).

    Then draw a random sample data of y values and plot against time, labeling the y-axis ticks based on the full set labels. Note that we still use set_yticks() first with numerical markers, and then replace with our category labels with set_yticklabels().

    labels = np.array(['A','B','C','D','E','F','G'])
    N = 4
    
    # example data
    times = pd.date_range(start='2017-10-17 00:00', end='2017-10-17 5:00', freq='H')
    data = np.random.choice(np.arange(len(labels)), size=len(times))
    
    fig, ax = plt.subplots(figsize=(15,10))
    ax.plot(times, data, marker='o', linestyle="None")
    ax.set_yticks(np.arange(len(labels)))
    ax.set_yticklabels(labels)
    plt.xlabel("time")
    

提交回复
热议问题