【问题标题】:python matplotlib edit histogrampython matplotlib 编辑直方图
【发布时间】:2016-12-18 00:02:25
【问题描述】:

我使用 matplotlib 创建直方图。仍然有一些问题我无法靠自己或借助互联网解决。

  1. 如何更改某些垃圾箱的颜色?具体来说,我想用以下方式更改箱的颜色:a.) 值 bin 1.25 红色?

  2. 如何不仅用带 1 个小数的数字而且用 2 个小数标记 X 轴(现在根本没有绘制)?

    import matplotlib.pyplot as plt
    import numpy as np
    import csv
    
    thickness = []  #gets thickness from list
    bins = [1.00,1.01,1.02,1.03,1.04,1.05,1.06,1.07,1.08,1.09,1.10,1.11,1.12,1.13,1.14,1.15,1.16,1.17,1.18,1.19,1.20,1.21,1.22,1.23,1.24,1.25,1.26,1.27,1.28,1.29,1.30,1.31,1.32,1.33,1.34,1.35,1.36,1.37,1.38,1.39,1.40,1.41,1.42,1.43,1.44,1.45,1.46,1.47,1.48,1.49,1.50
    ] #set bins manuelly
    
    with open('control.txt','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        #x.append(float(row[0]))
        thickness.append(float(row[1]))
    
    plt.hist(thickness, bins, align='left', histtype='bar', rwidth=0.8, color='green')
    
    plt.xlabel('thickness [mm]')
    plt.ylabel('frequency')
    plt.title('Histogram')
    plt.show()
    

请参见下面绘制的直方图:

plt.histogram so far

【问题讨论】:

    标签: python matplotlib colors decimal bins


    【解决方案1】:

    类似这样的东西(可能有一些错误):

    import matplotlib.pyplot as plt
    import numpy as np
    import csv
    from matplotlib.ticker import FormatStrFormatter
    
    
    thickness = []  #gets thickness from list
    bins = [1.00,1.01,1.02,1.03,1.04,1.05,1.06,1.07,1.08,1.09,1.10,1.11,1.12,1.13,1.14,1.15,1.16,1.17,1.18,1.19,1.20,1.21,1.22,1.23,1.24,1.25,1.26,1.27,1.28,1.29,1.30,1.31,1.32,1.33,1.34,1.35,1.36,1.37,1.38,1.39,1.40,1.41,1.42,1.43,1.44,1.45,1.46,1.47,1.48,1.49,1.50
    ] #set bins manuelly
    
    with open('control.txt','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        #x.append(float(row[0]))
        thickness.append(float(row[1]))
    
    h,bins = plt.hist(thickness, bins)
    plt.clf()
    fig, ax = plt.subplots()
    ax.bar(bins[bins<1.2],h[bins<1.2],rwidth=0.8, color='red')
    plt.bar(bins[np.logical_and(bins>1.2,bins<1.5)],h[np.logical_and(bins>1.2,bins<1.5)],rwidth=0.8, color='green')
    ax.bar(bins[bins>1.5],h[bins>1.5],rwidth=0.8, color='red')
    
    ax.set_xlabel('thickness [mm]')
    
    ax.set_ylabel('frequency')
    ax.set_title('Histogram')
    
    ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))  
    plt.show()
    

    【讨论】:

    • 感谢您的快速帮助。我现在尝试使用您的代码。我是编程新手,我只能假设你在这里做了什么。我得到错误:“h,bins = plt.hist(thickness, bins)ValueError: too many values to unpack (expected 2)”。你能帮我修复这个错误吗?
    • 是的,问题是函数返回的字段多于两个。对于那个很抱歉。这应该有效:h,bins,rest = plt.hist(thickness, bins)。代码记录条形图的 bin 和高度,然后清理图像 (plt.clf()),然后绘制条形图。
    猜你喜欢
    • 2016-04-26
    • 2017-06-29
    • 2019-02-13
    • 2014-04-15
    • 2021-12-18
    • 2016-10-14
    • 2011-07-16
    • 1970-01-01
    • 2012-01-12
    相关资源
    最近更新 更多