jva*_*nti 2 python plot matplotlib pandas
我有一个数据框,df我曾经生成两个系列的图,如下所示:
year = [2002, 2002, 2002, 2002]
month = ['Jan', 'Feb', 'Mar', 'Apr']
column1 = [3.3, 3.0, 3.1, 3.2, 2.9]
column2 = [7.0, 7.1, 7.3, 6.9, 7.3]
Dataset = list(zip(year, month, column1, column2))
df = DataFrame(data = Dataset, columns = ['year', 'month', 'column1', 'column2'])
df['column1'].plot(legend = True, label = 'column1')
df['column2'].plot(legend = True, label = 'column2', title = \
"Figure 1", style = '--', linewidth = 2.5)
Run Code Online (Sandbox Code Playgroud)
产生以下结果:
我的数据框中还有一列,df['year']其中包含我希望沿 x 轴移动的值。我尝试了以下方法
plt.xticks(df['year'])
Run Code Online (Sandbox Code Playgroud)
但发生了以下情况:
有没有办法使用该列df['year']并将其值作为 x 轴刻度线,而无需手动列出它们?我希望最终版本看起来像第一个图,但df['year']沿 x 轴具有唯一的值。
要将刻度标签设置为某些数据帧列的值,您需要将刻度位置设置为数据帧的索引,并将标签设置为所述列中的值。
plt.xticks(df.index,df["year"].values)
Run Code Online (Sandbox Code Playgroud)
完整示例:
from pandas import DataFrame
import matplotlib.pyplot as plt
year = [2002, 2002, 2002, 2002]
month = ['Jan', 'Feb', 'Mar', 'Apr']
column1 = [3.3, 3.0, 3.1, 3.2, 2.9]
column2 = [7.0, 7.1, 7.3, 6.9, 7.3]
Dataset = list(zip(year, month, column1, column2))
df = DataFrame(data = Dataset, columns = ['year', 'month', 'column1', 'column2'])
df['column1'].plot(legend = True, label = 'column1')
df['column2'].plot(legend = True, label = 'column2', title = \
"Figure 1", style = '--', linewidth = 2.5)
plt.xticks(df.index,df["year"].values)
plt.show()
Run Code Online (Sandbox Code Playgroud)
这当然将所有标签显示为 2002 年,因为年份列中的所有值都是 2002 年。(但不确定这是否有意义。)
如果您只想标记每年的第一次出现,您可以使用独特的年份,如下所示
unique_years, ind = np.unique(df["year"].values,return_index=True)
plt.xticks(df.index[ind], unique_years)
Run Code Online (Sandbox Code Playgroud)
导致这样的结果:
| 归档时间: |
|
| 查看次数: |
16879 次 |
| 最近记录: |