当前位置:网站首页>Making unequal interval histogram with Matplotlib

Making unequal interval histogram with Matplotlib

2022-06-22 01:23:00 JECK_ ケーキ

I've been working on a project recently , Histogram is required , But we need different spacing ,x The axes need to be set at unequal intervals . Baidu a pile of , No solution has been found , I found one later , It's actually a bar chart , Use a bar chart , Replace with histogram . Therefore, it can not be regarded as histogram .

Record the process .

My data is like this .

There are two columns , These two columns of data should be placed in a square diagram , And it is unequal spacing . And the data are not uniform , If equispaced , It is possible to cause a lot of straight sides to be very small , Not beautiful .

 

therefore , Change your mind . utilize numpy Of histogram, First, make a histogram sequence with unequal spacing , Then use the bar graph , Draw the group distance and the height of the sequence .

The code is as follows :

import re
import pandas as pd
import os
from collections import Counter
import time
import requests
from scrapy import Selector
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=15)


bins = [0, 1, 2, 3, 4, 5, 10, 20, 50, 100, 200]
height = [ np.histogram(xs, bins=bins)[0] for xs in [pro_all, pro_valid]]
left, n = np.arange(len(bins)-1), len(height)

fig, ax = plt.subplots()

for j, h in enumerate(height):
    ax.bar(left + j/n, h, width = 1.0/n, label = leg[j])

ax.set_xticks(np.arange(0, len(bins)))
ax.set_xticklabels(map(str, bins))
plt.legend(loc = 'upper right')

Make it out , It turns out like this .

 

  In the process , be aware numpy Of histogram The data returned is like this .

This data , It is based on group spacing , Frequency of separate statistics .

such as pro_all This variable , stay 0, The number of this group is 0 individual , stay 1 The number of this group is 928 individual , alike

pro_valid This variable , stay 0 The number of this group is 826 individual , stay 1 The number of this group is 728 individual .

The following data are based on bins This list corresponds to . Just the number of groups , Than bins Less length 1. Because the last group is interval 100-200, in other words ,pro_all Variable , stay 100-200 The number between is 5 individual , stay 50-100 The number between is 25 individual .

therefore , Is to use the group spacing as the horizontal axis , Height as the height of the bar , Made a bar chart . And then in settings x The scale of the coordinate axis . Add a legend or something .

 

原网站

版权声明
本文为[JECK_ ケーキ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220027122532.html