想要根据 Python 文本文件中的数据绘制条形图

好的,我很困惑,根本没有取得任何进展。python 新手,使用 Pycharm/python 3

我的桌面上保存了一个文本文件 (Win 10)。该文件包含一个名称、一个逗号和一个数字。

例如

姓名1,号码

姓名2,号码

姓名3,号码

名字4,号码

(ETC)

名字都不一样,编号也不分先后,有的相同有的不一样。

这些数字是整数,我要做的就是绘制条形图。x 轴上的名称和 y 轴上的数字(按降序排列)。

我试了又试,试了又试,但我无法让它工作。

我可以设法访问该文件,但无法对其执行任何操作。我可以获得我想要的输出,但我无法访问它。我可以得到点点滴滴,但我不能把它们放在一起。我知道这可能是一件容易的事情,但没有任何意义,而且似乎没有任何效果,并且可以用手。

你怎么做到这一点?


吃鸡游戏
浏览 87回答 2
2回答

慕森卡

我认为这将是最简单的实现:#import libraries import pandas as pd import matplotlib.pyplot as plt #read your txt file which is formatted as a csv into a dataframe and name your colsdf = pd.read_csv('my_file.txt',names=['name','number'])print(df.head())#plot itplt.bar(df.name,df.number) #this is equivalent to df['name'],df['number']plt.show()还有很多其他方法可以使它变得更复杂,改进您的绘图以确保您的数据类型正确等,但这有望帮助您前进。

宝慕林4294392

这样的事情会起作用。如果您有任何问题,请告诉我。import matplotlib.pyplot as pltfilepath = r"C:\Users*me*\Desktop\my_file.txt"with open(filepath) as file:    entries = [x.split(",") for x in file.readlines()] # Read the text, splitting on comma.    entries = [(x[0],int(x[1])) for x in entries] # Turn the numbers into ints.    entries.sort(key=lambda x:x[1], reverse=True) # Sort by y-values.    x_coords = [x[0] for x in entries]    y_coords = [x[1] for x in entries]    plt.bar(x_coords,y_coords) # Draw a bar chart    plt.show()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python