在python3中绘制(直方图) [英] Plotting in python3 (histogram)
问题描述
我正在尝试从一系列成绩创建直方图.所有等级均为可能的7级等级之一(-3、0、2、4、7、10、12).
我正在使用下面的代码来生成绘图,但是我无法确定将 x 轴标签放在条形中间的方法,删除绘图中间的空间,并可能在它们之间放置一个小空间酒吧...
将matplotlib.pyplot导入为pltfinalGrades = [-3,-3、10、2、10、0、7、7、12,-3、7、0、12、12、12、12、12、0、0、0、4]plt.hist(finalGrades,bins = 8)plt.xticks([-3, 0, 2, 4, 7, 10, 12])plt.title(最终成绩图")plt.xlabel("所有可能的成绩")plt.ylabel(学生人数")plt.show()
一个人需要了解数字不能在小节的中间,因为它们恰好在应有的位置.(如果将 0 与 -3 与 2 一样接近,数学之神会开始哭泣.)
因此,您要的是类别值的直方图,而不是数值的直方图.已经有一些与分类直方图有关的问题,例如,参见
-
I am trying to create a histogram from an array of grades. All the grades are one of the possible 7-scale (-3, 0, 2, 4, 7, 10, 12).
I am using the below code to generate the plot, however I cannot identify a way to put the x-axis label on the middle of the bars, remove the space in the middle of the plot and maybe put a small space between the bars...
import matplotlib.pyplot as plt finalGrades = [-3, -3, 10, 2, 10, 0, 7, 7, 12, -3, 7, 0, 12, 12, 12 ,12, 12, 0, 0, 0, 4] plt.hist(finalGrades, bins=8) plt.xticks([-3, 0, 2, 4, 7, 10, 12]) plt.title("Final Grades plot") plt.xlabel("All possible grades") plt.ylabel("Number of students") plt.show()
解决方案One needs to understand that the numbers cannot be in the middle of the bar, since they are at exactly those positions where they should be. (If you put 0 as close to -3 as to 2, the gods of mathematics will start crying.)
So what you are asking for here is a histogram of categorial values, not numerical ones. There are some questions related to categorial histograms already, see, e.g.
- How to make a histogram from a list of strings in Python?
- Hist in matplotlib: Bins are not centered and proportions not correct on the axis
What you need to do, is to think of the grades
-3
,0
,2
etc. as category (likered
,green
,yellow
) and the question is now how often each category is represented in the listfinalGrades
. Sincematplotlib.hist
only understands numerical data, we would map then
categories to the firstn
integers,-3 -> 0
,0 -> 1
,2 -> 2
and so forth.
Now instead of a list of grades
[-3, -3, 10, 2, 10, 0, ...]
we have a list of category numbers
[0, 0, 5, 2, 5, 1, ...]
and those category numbers are equally spaced, such that the histogram will understand what we want. The histogram can then be plotted withbins = [0,1,2, ... , 6,7]
(we need 8 bin edges to get 7 bins). Finally, and funnily enough,align='left'
makes the bins centered at the tickmarks. The tickmarks are then set to be the categorial values, i.e. the possible grades.import matplotlib.pyplot as plt finalGrades = [-3, -3, 10, 2, 10, 0, 7, 7, 12, -3, 7, 0, 12, 12, 12 ,12, 12, 0, 0, 0, 4] possibleGrades = [-3, 0, 2, 4, 7, 10, 12] fin = [ possibleGrades.index(i) for i in finalGrades] plt.hist(fin, bins=range(8), align="left") plt.xticks(range(7), possibleGrades) plt.title("Final Grades plot") plt.xlabel("All possible grades") plt.ylabel("Number of students") plt.show()
这篇关于在python3中绘制(直方图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!