修改柱状图中的X轴刻度。

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

Change axis x scale in a bar chart

问题

我发现自己正在通过柱状图来绘制一个名为“barras”的DataFrame,其中包含了从2017年到2022年每个月的数据。每个月都有三列数据,分别命名为“% PRINCIPAL”,“% APORTES”和“% ΔE”。我希望能够绘制从2009年开始的柱状图,即使没有数据,只有每个月的第一个月和第六个月出现在x轴标签上,但我无法实现这一点。

这是我的DataFrame:

  1. % PRINCIPAL % APORTES % ΔE
  2. FECHA
  3. 2017-03 25.974253 42.430129 31.595618
  4. 2017-04 131.728602 27.057582 -58.786184
  5. 2017-05 144.069530 17.564611 -61.634142
  6. 2017-06 116.492102 25.948196 -42.440299
  7. 2017-07 95.677079 42.383666 -38.060745
  8. ...
  9. 2022-05 86.728444 46.208640 -32.937084
  10. 2022-06 87.980394 58.643608 -46.624002
  11. 2022-07 73.873644 53.591839 -27.465483
  12. 2022-08 72.113597 44.375137 -16.488734
  13. 2022-09 52.777619 79.301887 -32.079506

这是我用来绘制图形的代码:

  1. barras = pd.concat([I['% PRINCIPAL'], I['% APORTES'], I['% ΔE']], axis=1)
  2. barras.index = pd.to_datetime(barras.index).strftime('%Y-%m')
  3. barras.plot(kind="bar", stacked=True, color=['b', 'g', 'r'], edgecolor='black', width=1, alpha=0.77, figsize=(16, 8))
  4. plt.title('PORCENTAJES DE CAUDAL EN TRAMO I')
  5. plt.ylabel("Caudal (%)")
  6. plt.xlabel('Fecha')
  7. plt.legend(loc='best')
  8. plt.savefig("BLOQUE I.png", bbox_inches="tight", dpi=160)

结果是:

修改柱状图中的X轴刻度。

我想要相同的图形,但从2009年开始,每六个月显示一个x轴标签。

我希望得到类似这样的效果(我用Photoshop制作了它):

修改柱状图中的X轴刻度。

英文:

I find myself graphing by means of bars a Dataframe that I have called barras that contains data from 2017 to 2022, for months. In each month there are 3 columns with data denominated as % PRINCIPAL, % APORTES y % E. I wanted to be able to graph the bars since 2009, even if there is no data, and that only the 1st and 6th months of each month appear on the x-axis labels, but I can't do it.

This is the Dataframe:

  1. % PRINCIPAL % APORTES % ΔE
  2. FECHA
  3. 2017-03 25.974253 42.430129 31.595618
  4. 2017-04 131.728602 27.057582 -58.786184
  5. 2017-05 144.069530 17.564611 -61.634142
  6. 2017-06 116.492102 25.948196 -42.440299
  7. 2017-07 95.677079 42.383666 -38.060745
  8. ... ... ...
  9. 2022-05 86.728444 46.208640 -32.937084
  10. 2022-06 87.980394 58.643608 -46.624002
  11. 2022-07 73.873644 53.591839 -27.465483
  12. 2022-08 72.113597 44.375137 -16.488734
  13. 2022-09 52.777619 79.301887 -32.079506

And this is my code to do the graphic:

  1. barras = pd.concat([I['% PRINCIPAL'],I['% APORTES'],I['% ΔE']], axis=1)
  2. barras.index = pd.to_datetime(barras.index).strftime('%Y-%m')
  3. barras.plot(kind="bar",stacked=True, color = ['b','g','r'], edgecolor='black', width=1, alpha=0.77, figsize=(16,8))
  4. plt.title('PORCENTAJES DE CAUDAL EN TRAMO I')
  5. plt.ylabel("Caudal (%)")
  6. plt.xlabel('Fecha')
  7. plt.legend(loc='best')
  8. plt.savefig("BLOQUE I.png", bbox_inches="tight", dpi=160)

Result:

修改柱状图中的X轴刻度。

I want the same graphic but since 2009, and with the x-axis label each six moths.

I would like to get something like this (I've done it with photoshop):

修改柱状图中的X轴刻度。

答案1

得分: 1

你可以将你的数据框与包含你感兴趣的其余日期的另一个数据框连接起来,然后绘制它。

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. # 创建虚拟数据
  5. dates = pd.date_range('2/2017', '8/2022', freq='M')
  6. values = np.random.uniform(-100, 100, (len(dates), 3))
  7. barras = pd.DataFrame(values, columns=['% PRINCIPAL', '% APORTES', '% ΔE'], index=dates)
  8. # 创建包含从2009年开始的日期的新数据框
  9. add_dates = pd.date_range('1/2009', barras.index[0], freq='M')[:-1]
  10. df_0 = pd.DataFrame(0, columns=['% PRINCIPAL', '% APORTES', '% ΔE'], index=add_dates)
  11. # 将所有数据连接到一个数据框中
  12. barras = pd.concat([df_0, barras])
  13. # 绘图
  14. fig, ax = plt.subplots(1, 1, figsize=(16, 8))
  15. barras.set_index(barras.index.strftime('%Y-%m')).plot(
  16. kind="bar",
  17. stacked=True,
  18. color=['b', 'g', 'r'],
  19. edgecolor='black',
  20. width=1,
  21. alpha=0.77,
  22. ax=ax
  23. )
  24. new_ticks = ax.get_xticks()[barras.index.month.isin([1, 1+6])]
  25. ax.set_xticks(new_ticks)
  26. plt.title('PORCENTAJES DE CAUDAL EN TRAMO I')
  27. plt.ylabel("Caudal (%)")
  28. plt.xlabel('Fecha')
  29. plt.legend(loc='best')
  30. plt.savefig("BLOQUE I.png", bbox_inches="tight", dpi=160)

编辑:现在代码显示所有数据,并且时间线是正确的。

英文:

You can concatenate your dataframe with another one containing the rest of the dates you are interested in and then plot that.

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. # Create dummy data
  5. dates = pd.date_range('2/2017', '8/2022', freq='M')
  6. values = np.random.uniform(-100, 100, (len(dates), 3))
  7. barras = pd.DataFrame(values, columns=['% PRINCIPAL', '% APORTES', '% ΔE'], index=dates)
  8. # Create new dataframe with 0s for dates starting from 2009
  9. add_dates = pd.date_range('1/2009', barras.index[0], freq='M')[:-1]
  10. df_0 = pd.DataFrame(0, columns=['% PRINCIPAL', '% APORTES', '% ΔE'], index=add_dates)
  11. # Concatenate everything into a single dataframe
  12. barras = pd.concat([df_0, barras])
  13. # Plot
  14. fig, ax = plt.subplots(1,1, figsize=(16,8))
  15. barras.set_index(barras.index.strftime('%Y-%m')).plot(
  16. kind="bar",
  17. stacked=True,
  18. color = ['b','g','r'],
  19. edgecolor='black',
  20. width=1,
  21. alpha=0.77,
  22. ax=ax
  23. )
  24. new_ticks = ax.get_xticks()[barras.index.month.isin([1,1+6])]
  25. ax.set_xticks(new_ticks)
  26. plt.title('PORCENTAJES DE CAUDAL EN TRAMO I')
  27. plt.ylabel("Caudal (%)")
  28. plt.xlabel('Fecha')
  29. plt.legend(loc='best')
  30. plt.savefig("BLOQUE I.png", bbox_inches="tight", dpi=160)

EDIT: Now the code shows all the data and the temporal line is right.

修改柱状图中的X轴刻度。

huangapple
  • 本文由 发表于 2023年3月15日 19:18:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743989.html
匿名

发表评论

匿名网友

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

确定