在Python中从CSV文件创建混合图表

2024-09-23 09:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我开发了一个perl脚本来处理数据并给我一个最终的csv文件。不幸的是,我的系统不支持perl中的图形和图表包,由于工作限制,我无法安装它们。所以我想尝试使用csv文件,在Python中组合一些东西来生成一个混合图。我希望第一列是x轴上的标签。接下来的三列是条形图。第四列是横穿x轴的一条线。在

以下是示例数据:

Name      PreviousWeekProg     CurrentWeekProg     ExpectedProg     Target
Dan              94                   92                 95           94
Jarrod           34                   56                 60           94
Chris            45                   43                 50           94
Sam              89                   90                 90           94
Aaron            12                   10                 40           94
Jenna            56                   79                 80           94
Eric             90                   45                 90           94

我在找这样的图表: enter image description here

我做了一些研究,但是由于我在python中的无知,我想征求一些关于在python中混合使用图表和图形的好模块的指导。对不起,如果我的帖子模糊不清的话。除了在网上看其他的参考资料,我对如何做这件事一无所知。另外,我的python版本是3.8,而且我确实安装了matplotlib(这是之前建议我使用的)。在


Tags: 文件csv数据name脚本图形示例系统
3条回答

由于@ShaunLowis的答案没有包含完整的示例,我想我应该添加一个。就读取.csv文件而言,在这种情况下,最好的方法可能是使用^{},正如另一个答案所指出的那样。在本例中,我将文件命名为test.csv,并将其放在运行脚本的同一目录中

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.read_csv("./test.csv")
names = df['Name'].values
x = np.arange(len(names))
w = 0.3
plt.bar(x-w, df['PreviousWeekProg'].values, width=w, label='PreviousWeekProg')
plt.bar(x, df['CurrentWeekProg'].values, width=w, label='CurrentWeekProg')
plt.bar(x+w, df['ExpectedProg'].values, width=w, label='ExpectedProg')
plt.plot(x, df['Target'].values, lw=2, label='Target')
plt.xticks(x, names)
plt.ylim([0,100])
plt.tight_layout()
plt.xlabel('X label')
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.1), fancybox=True, ncol=5)
plt.savefig("CSVBarplots.png", bbox_inches="tight")
plt.show()

enter image description here


解释

pandas文档中,read_csv()(排除了与示例无关的参数)

pandas.read_csv(filepath_or_buffer)

Read a comma-separated values (csv) file into DataFrame.

filepath_or_buffer: str, path object or file-like object

Any valid string path is acceptable. The string could be a URL. [...] If you want to pass in a path object, pandas accepts any os.PathLike.

By file-like object, we refer to objects with a read() method, such as a file handler (e.g. via builtin open function) or StringIO.

在本例中,我指定的是文件的路径,而不是文件对象。在

^{pr2}$

这将提取'Name'列中的值并将其转换为^{}对象。为了绘制一个名称的多个条形图,我引用了this answer。但是,为了使用这个方法,我们需要一个与names数组长度相同的浮点数组,因此

x = np.arange(len(names))

然后设置条的宽度并相应地偏移第一条和第三条,如referenced answer中的轮廓

w = 0.3
plt.bar(x-w, df['PreviousWeekProg'].values, width=w, label='PreviousWeekProg')
plt.bar(x, df['CurrentWeekProg'].values, width=w, label='CurrentWeekProg')
plt.bar(x+w, df['ExpectedProg'].values, width=w, label='ExpectedProg')

^{}页(排除未使用的非位置参数)

matplotlib.pyplot.bar(x, height, width=0.8)

The bars are positioned at x [...] their dimensions are given by width and height.

Each of x, height, and width may either be a scalar applying to all bars, or it may be a sequence of length N providing a separate value for each bar.

在本例中,x和{}是值序列(每个条不同),而width是一个标量(每个条都是相同的)。在

接下来是target的行,它非常简单,只需根据'Target'列中的值绘制前面创建的x

plt.plot(x, df['Target'].values, lw=2, label='Target')

其中lw指定线宽。免责声明:如果.csv的每一行的目标值都不相同,则此操作仍然有效,但可能与您希望的不完全相同。在

接下来的两行

plt.xticks(x, names)
plt.ylim([0,100])

只需在适当的x位置添加这些名称,然后设置y限制来跨越[0, 100]。在

最后一点是在情节下方添加图例

plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True)

请参阅this answer,了解如何根据需要调整此值。在

您可以使用包seaborn中的参数hue。首先,需要使用函数melt重塑数据集:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

df1 = df.melt(id_vars=['Name', 'Target'])
print(df1.head(10))

输出:

^{pr2}$

现在您可以使用列'variable'作为函数barplot中的hue参数:

fig, ax = plt.subplots(figsize=(10, 5)) # set the size of a figure
sns.barplot(x='Name', y='value', hue='variable', data=df1) # plot

xmin, xmax = plt.xlim() # get x-axis limits
ax.hlines(y=df1['Target'], xmin=xmin, xmax=xmax, color='red') # add multiple lines
# or ax.axhline(y=df1['Target'].max()) to add a single line

sns.set_style("whitegrid") # use the whitegrid style
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.06), ncol=4, frameon=False) # move legend to the bottom
plt.title('Student Progress', loc='center') # add title
plt.yticks(np.arange(df1['value'].min(), df1['value'].max()+1, 10.0)) # change tick frequency
plt.xlabel('') # set xlabel
plt.ylabel('') # set ylabel

plt.show() # show plot

enter image description here

我建议您使用Pandas库的'read_csv()'实用程序读取.csv文件,如下所示:

import pandas as pd

df = pd.read_csv(filepath)

对象存储在这个信息框中。然后可以通过以下方式访问列:

^{pr2}$

之后您可以拨打:

my_column.plot(kind='bar')

在你想画的任何一列上。 配置子批次是另一种方法,我建议使用matplotlibpyplot。在

我建议从这个figure和axis对象声明开始,然后从那里开始:

fig = plt.figure()
ax1 = plt.subplot()
ax2 = plt.subplot()
ax3 = plt.subplot()
ax4 = plt.subplot()

在这里您可以阅读更多关于添加轴数据here。在

让我知道如果这有帮助!在

相关问题 更多 >