首页 > 解决方案 > 如何从 csv 文件中获取 Python 中 x 轴上的所有数据

问题描述

CSV 文件:

Words,Count
ca,110
tc,103
cg,103
gt,100
cc,98
at,96
gc,95
ct,95
aa,94
ta,94
ac,94
tt,91
ag,87
gg,84
ga,79
tg,77

代码:

from matplotlib import pyplot as plt
import pandas as pd
df = pd.read_csv('file.csv')
df.plot(kind='line', x='Words', y='Count',logx=True,logy=True)
plt.show()

当我得到我的情节时,我看到了这个: 点击这里

我如何从 CSV 文件中获取我的 X 轴上的所有这些字母,因为我只有例如 ac 和 tc ?

更新

当我使用如下所示的 CSV 文件时,我现在遇到了另一个问题:

Words,Count
tgc,25
tca,24
agt,22
gac,22
gtc,22
cag,21
caa,21
ctg,21
act,21
atg,20
aaa,20
aat,20
cgt,20
att,20
gta,20
ttc,19
cct,19
ctt,18
agc,18
gct,18
cgg,18
ata,18
aag,18
tac,18
aca,18
cac,18
gtt,17
ggg,17
cgc,17
cta,17
gcc,17
cca,17
tcc,16
acc,16
tcg,16
atc,16
aga,15
gat,15
gtg,15
ttt,15
tat,15
gaa,14
tct,14
ccg,14
ggt,14
acg,13
gga,13
ccc,13
aac,12
gca,12
tgg,12
tta,12
cga,12
ctc,11
gag,11
gcg,11
agg,11
cat,11
ttg,11
ggc,9
tgt,9
tga,1

我的情节看起来像这样:点击这里 有没有机会在我的 x 轴上清楚地看到一切?我现在的代码:

df = pd.read_csv("file2.csv")

ax=df.plot(kind='line', y='Count',logx=False,logy=True)
ax.xaxis.set_ticks(df.index)
ax.xaxis.set_ticklabels(df['Words'])
plt.figure(figsize=(10,30))
plt.show()

标签: pythonpandascsvmatplotlibplot

解决方案


对刻度使用索引,对标签使用系列。

...
ax = df.plot(kind='line', y='Count')
ax.xaxis.set_ticks(df.index)
ax.xaxis.set_ticklabels(df['Words'])
plt.show()

要不就:

df.plot(x='Words',y='Count',xticks=df.index)


推荐阅读