简体   繁体   English

如何使用输入 *.txt 文件绘制一个非常简单的条形图(Python、Matplotlib)?

[英]How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

I use Python 2.7 and matplotlib.我使用 Python 2.7 和 matplotlib。 I have a *.txt data file :我有一个 *.txt 数据文件:

0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014

first column of my file (numbers) should be on axis Y in my bar chart, and the second column from my file (dates) should be on axis OX in my histogram.我的文件(数字)的第一列应该在我的条形图中的 Y 轴上,我的文件(日期)的第二列应该在我的直方图中的 OX 轴上。 I only know how to read the file:我只知道如何读取文件:

OX = []
OY = []

try :
    with open('data.txt', 'r') as openedFile :
        for line in openedFile :
            tab = line.split()
            OY.append(int(tab[0]))
            OX.append(str(tab[1]))
except IOError :
    print("IOError!")

I did read a matplotlib docs but it still doesn't help me.我确实阅读了 matplotlib 文档,但它仍然没有帮助我。 I would also like to add dates I read to my bar chart, to make it look like我还想将我阅读的日期添加到条形图中,使其看起来像

这个

Could someone please help me?有人可以帮我吗?

You're talking about histograms, but this doesn't quite make sense.你说的是直方图,但这不太合理。 Histograms and bar charts are different things.直方图和条形图是不同的东西。 An histogram would be a bar chart representing the sum of values per year, for example.例如,直方图可以是表示每年值总和的条形图。 Here, you just seem to be after bars.在这里,您似乎只是在追求酒吧。

Here is a complete example from your data that shows a bar of for each required value at each date:以下是来自您的数据的完整示例,其中显示了每个日期的每个必需值的条形:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer ).您需要使用strptime解析日期并将 x 轴设置为使用日期(如本答案中所述)。

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:如果您对让 x 轴显示线性时间刻度不感兴趣,而只想显示带有标签的条形,您可以这样做:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):编辑:以下评论,对于所有的刻度线,并且为了让它们居中,将范围传递给set_ticks (并将它们移动条形宽度的一半):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

This code will do what you're looking for.这段代码会做你正在寻找的。 It's based on examples found here and here .它基于在此处此处找到的示例。

The autofmt_xdate() call is particularly useful for making the x-axis labels readable. autofmt_xdate()调用对于使 x 轴标签可读特别有用。

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)

fig.autofmt_xdate()

plt.savefig("figure.pdf")

在此处输入图片说明

First, what you are looking for is a column or bar diagram , not really a histogram.首先,您要查找的是柱形图条形图,而不是真正的直方图。 A histogram is made from a frequency distribution of a continuous variable that is separated into bins.直方图由连续变量的频率分布构成,该变量被分成多个区间。 Here you have a column against separate labels.在这里,您有一个针对单独标签的列。

To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar() method.要使用 matplotlib 制作条形图,请使用matplotlib.pyplot.bar()方法。 Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.看看 matplotlib 文档的这个页面,它很好地解释了示例和源代码如何做到这一点。

If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better.如果可能的话,我只是建议对于像这样的简单任务,如果您可以避免编写更好的代码。 If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'.如果您有任何电子表格程序,这应该是小菜一碟,因为这正是它们的用途,您不必“重新发明轮子”。 The following is the plot of your data in Excel:以下是您在 Excel 中的数据图:

Excel 中的条形图

I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.我只是从问题中复制了您的数据,使用文本导入向导将其分成两列,然后插入了一个列图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中使用matplotlib绘制带有标签的简单条形图? - how to draw a simple bar chart with labels in python using matplotlib in python? 如何在python中使用matplotlib绘制叠加条形图? - How to plot a superimposed bar chart using matplotlib in python? plot 条形图网格或包装条形图使用 python (matplotlib) - plot grid of bar charts or wrap bar chart using python (matplotlib) 使用pandas和Matplotlib中的csv数据在python中绘制条形图 - Plot bar chart in python using csv data in pandas & Matplotlib 如何使用 python 从 csv 文件中获取 plot 条形图? - How to plot bar chart(s) from csv file using python? 如何使用 python 中 matplotlib 中的相同 plt plot 并保存饼图和条形图 - How to plot and save pie chart and bar graph using same plt from matplotlib in python 如何使用 matplotlib 在 python 条形图中绘制可变数量的集合? - How do I plot a variable number of sets in a python bar chart using matplotlib? 如何在 python 中使用 matplotlib 对时间序列数据进行 plot 堆积条形图? - How to plot a stacked bar chart on time series data using matplotlib in python? 如何使用matplotlib.pyplot在Python中绘制条形图? 参数高度必须为“ xxxx”或标量 - How to plot bar chart in Python using matplotlib.pyplot ? Argument height must be 'xxxx' or scalar 使用matplotlib在python中绘制漂亮的条形图 - Pretty plot bar chart in python with matplotlib
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM