使用pandas和Python绘制x轴的折线图。

huangapple go评论112阅读模式
英文:

Line plot x axis using pandas python

问题

  1. 结果
  2. 年份 月份 最小天数 平均天数 中位数天数 计数
  3. 2015 1 9 12.56666666 10 4
  4. 2015 2 10 13.67678788 9 3
  5. ........................................................
  6. 2016 12 12 15.7889990 19 2
  7. 以此类推...
  8. 我想创建一个折线图,根据年份和月份来绘制最小天数、平均天数、中位数天数和计数。我该如何做?
  9. 到目前为止尝试的代码
  10. axes = result.plot.line(subplots=True)
  11. type(axes)
  12. 这个代码运行得很好,但我也得到了年份和月份的子图。我希望年份和月份在x轴上。
  13. **尝试的代码2:**
  14. import matplotlib.pyplot as plt
  15. fig, ax = plt.subplots()
  16. result.groupby('年份').plot(x='年份', y='中位数天数', ax=ax, legend=False)
  17. 这段代码的问题是它只按年份分组。我需要月份(20151月,20152月等)。另一个问题是这给我一个单一的子图用于中位数。如何添加均值、最小值等子图?
  18. **编辑:**
  19. P.S. 如果有人可以回答,如果月份整数被替换为月份名称(一月、二月等),那将是很棒的。
英文:

result

  1. year Month Min_days Avg_days Median_days Count
  2. 2015 1 9 12.56666666 10 4
  3. 2015 2 10 13.67678788 9 3
  4. ........................................................
  5. 2016 12 12 15.7889990 19 2
  6. and so on...

I wish to create a line plot plotting min_days, avg_days, median_days, count according to month and year say. how can I do that

Codes tried till now

  1. axes = result.plot.line(subplots=True)
  2. type(axes)

This works great but I m also getting subplots of year and month. I want year and month to be on x axis

Code2 tried:

  1. import matplotlib.pyplot as plt
  2. fig, ax = plt.subplots()
  3. result.groupby('Year').plot(x='Year', y='Median_days', ax=ax, legend=False)

The issue with this code is it groupbys only year. I need month too (Jan 2015, Feb 2015 and so on). Also another issue is This gives me a single subplot for Median. How to add subplots for mean, min etc

Edit:
P.S. Also if someone can answer in case month int is replaced with month names (Jan, Feb etc. it would be great)

答案1

得分: 1

一个解决方法是首先创建一个年-月列:

  1. result["year-month"] = pd.to_datetime(
  2. result.year.astype(str) + "-" + result.Month.astype(str)
  3. )
  4. fig, ax = plt.subplots()
  5. for col in ["Min_days", "Avg_days", "Median_days", "Count"]:
  6. ax.plot(result["year-month"], result[col], label=col)
  7. ax.legend(loc="best")
  8. ax.tick_params(axis="x", rotation=30)

根据您提供的有限数据,您会得到:

使用pandas和Python绘制x轴的折线图。

英文:

One solution could be to first create a year-month column:

  1. result["year-month"] = pd.to_datetime(
  2. result.year.astype(str) + "-" + result.Month.astype(str)
  3. )
  4. fig, ax = plt.subplots()
  5. for col in ["Min_days", "Avg_days", "Median_days", "Count"]:
  6. ax.plot(result["year-month"], result[col], label=col)
  7. ax.legend(loc="best")
  8. ax.tick_params(axis="x", rotation=30)

With the limited data you've given us, you'll get:
使用pandas和Python绘制x轴的折线图。

huangapple
  • 本文由 发表于 2020年1月6日 18:46:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定