【问题标题】:Python - Plot a matplotlib histogram with 2 conditions on dataPython - 绘制具有 2 个数据条件的 matplotlib 直方图
【发布时间】:2016-01-31 17:29:16
【问题描述】:

我试图在数据上绘制具有两个条件的直方图,因为它会产生一些噪声,我想忽略低于 5 和高于 100 的值,所以当我绘制时我尝试使用:“data[data> 5 . 和数据

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import csv

Elements = open("C:/.../Desktop/test.txt","r")
data= np.genfromtxt(Elements,skip_header=0) 
Elements.close()

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(7, 5.3)


num_bins = 75
# the histogram of the data
n, bins, patches = plt.hist(data[data> 5. and data< 100.]*1.78,num_bins, facecolor='blue', alpha=0.5)

plt.xlabel('Feret',fontsize=18)
plt.ylabel('frequency',fontsize=18)
plt.xlim(0.,50.)
plt.tick_params(axis='both', which='major', labelsize=14)
# plt.tick_params(axis='both', which='minor', labelsize=8)
# plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
plt.savefig('Hist_GS_ext.png', dpi=1000)

# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15,bottom=0.2)
plt.show()

【问题讨论】:

  • 下次尝试自己进行一些探索:您的问题到底是什么。例如,这里与 95% 或您的代码没有任何关系:它只是 numpy 数组的逻辑索引。您的问题代码实际上可能只有 3 行。

标签: python matplotlib plot conditional-statements histogram


【解决方案1】:

您正在尝试按元素进行逻辑与,但使用了错误的语法。使用&amp; 代替and,并将各个表达式封装到括号中:

 data[(data>5.) & (data<100.)]

另一种方法是使用numpy函数logical_and

data[np.logical_and(data>5., data<100.)]

【讨论】:

    猜你喜欢
    • 2013-11-26
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多