【发布时间】:2020-06-02 14:49:05
【问题描述】:
我正在尝试使用pandas 和matplotlib 为python 中的csv 文件中的两种类型的变量及其计数制作比较条形图。每种类型的变量数据都存储在不同的目录中。
我为不同的数据和concate 创建了两个循环并绘制它们但是循环和附加数据存在问题。 第一种类型的变量数据没有附加到下一个文件,它总是使用第一个文件并与第 2 个变量类型的数据连接(正确附加)。
这是我正在使用的代码
path = '/scratch/plots/'
A_files = sorted(glob.glob(os.path.join(path, "*table.csv")))
path = '/scratch/plots/B/'
B_files = sorted(glob.glob(os.path.join(path, "*table.csv")))
# loop through the files and read them in with pandas
dataframes = [] # a list to hold all the individual pandas DataFrames
for csvfile in A_files:
df = pd.read_csv(csvfile,usecols = ['COUNT','CLASS'])
dataframes.append(df) #this case it is taking only first file to concate. Loop doest not appending correctly
dataframes2 = []
for x in B_files:
fn= os.path.splitext(x)[0]
df2 = pd.read_csv(x,usecols = ['COUNT','CLASS'])
dataframes2.append(df2)
A_df=df.iloc[2:12]
B_df=df2.iloc[2:12]
a= pd.concat([A_df,B_df], axis=1)
ax=a.set_index('CLASS').plot(kind='bar',rot=0, figsize=(15,10), fontsize=12)
ax.legend(["A", "B"]);
plt.savefig('' + fn[:-32]+'_bargraph' + '.png', dpi=300)
plt.show()
如何通过字典中的第一个循环追加每个文件?我附上了一个连接数据框和绘图的示例enter image description here
【问题讨论】:
-
我没有看到任何字典,你的意思是数据框吗?另外,你想循环什么?即班级,人数?
-
您是在寻找所有连接数据帧的单个图还是每个目录中每对数据的多个图?
-
@Parfait 我在一个文件夹中有 2 个日期的 2 个文件用于一个变量,而在另一个变量的其他文件夹中有类似的 2 个文件。我连接两个相同日期的 Class(x-axis) 和 Count(y-axis) 列以制作比较图。然而,第一个变量 Class 和 Count 没有与其他变量的相应日期连接,它只占用第一个文件并与其他第二个变量文件连接。请看一下我上面附上的图片中的数据。
-
请查看以下建议的同步循环是否满足您的需求。
-
@Parfait 非常感谢它的工作。我还有一个问题 - 如何将 A 和 B 的分类数据的总 CLASS (%) 并排绘制成堆积条形?可能使用
.groupby而不是使用stacked=True,它在每个类(%)的一个栏中将A 类和B 类相加。我希望这些 10-100% 的 CLASS 并排在一个 A 栏和 1 个 B 中。
标签: pandas loops csv matplotlib