我有一个数据框,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)
产生以下内容:
我的数据框中还有一列 df['year']
,其中包含我希望沿 x 轴移动的值。我尝试了以下
plt.xticks(df['year'])
但发生了以下情况:
有没有一种方法可以使用 df['year']
列并将其值作为 x 轴刻度线,而无需手动列出它们?我希望最终版本看起来像第一个图,但沿 x 轴具有 df['year']
的唯一值。
最佳答案
要将刻度标签设置为某些数据框列的值,您需要将刻度位置设置为数据框的索引,并将标签设置为所述列中的值。
plt.xticks(df.index,df["year"].values)
完整示例:
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()
这当然会将所有标签显示为 2002 年,因为年份列中的所有值都是 2002 年。(但不确定这是否有意义。)
如果你只想标记每年的第一次出现,你可以像下面这样使用独特的年份
unique_years, ind = np.unique(df["year"].values,return_index=True)
plt.xticks(df.index[ind], unique_years)
结果是这样的:
关于python - 使用数据框列更改 x 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48633654/