matplotlib 如何在使用twinx时添加图例

qgzx9mmu  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(146)

我试图用相同的x轴值(时间)但不同的y轴值绘制2个值。我试图在图中添加图例,但是,我总是为同一个变量获得2个图例,而不是每个变量一个图例。
这是我用过的代码。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.dates as mdates
  4. from datetime import datetime, timedelta
  5. # Assuming you have the time series data in numpy arrays named x_values, y_values, and fire_counts
  6. df=pd.read_csv('FireCountPenchMar2012.csv')
  7. print(df)
  8. xaxis=np.arange(0,248,1)
  9. yaxis=hdwi
  10. yaxis2=df.fire_count
  11. print(yaxis2)
  12. # Step 1: Create the dates for the x-axis based on the starting date (1 March 00:00 UTC)
  13. start_date = datetime(2023, 3, 1, 0, 0, 0)
  14. dates = [start_date + timedelta(hours=3*i) for i in range(len(xaxis))]
  15. plt.figure(figsize=(15,10))
  16. # Step 2: Plot the first time series with dates on the x-axis
  17. plt.plot(dates, yaxis, 'o-g', label='HDWI')
  18. # Step 3: Format the first y-axis and add axis labels and a title
  19. plt.ylabel('HDW')
  20. plt.title('HDWI v/s Fire Counts')
  21. # Step 4: Create a second y-axis for the 'fire_counts' variable
  22. ax2 = plt.gca().twinx()
  23. ax2.scatter(dates, yaxis2, color='red', label='Fire Counts')
  24. ax2.set_ylabel('Fire Counts')
  25. # Step 5: Show the legend for both lines (y_values and fire_counts)
  26. lines, labels = plt.gca().get_legend_handles_labels()
  27. lines2, labels2 = ax2.get_legend_handles_labels()
  28. # Combine the handles and labels for both legends
  29. all_lines = lines + lines2
  30. all_labels = labels + labels2
  31. # Display the combined legend
  32. plt.gca().legend(all_lines, all_labels)
  33. # Step 6: Format the x-axis to display dates at regular intervals (e.g., every 2 days)
  34. date_format = mdates.DateFormatter('%b %d')
  35. plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=2))
  36. plt.gca().xaxis.set_major_formatter(date_format)
  37. # Step 7: Rotate the x-axis date labels for better readability
  38. plt.xticks(rotation=45)
  39. # Step 8: Adjust the layout and display the plot
  40. plt.grid()
  41. plt.tight_layout()
  42. plt.show()here

此图中的图例应突出显示此问题
The figure as obtained in the output with repeating legend

krcsximq

krcsximq1#

有关详细说明,请参阅this answer

  1. from matplotlib.pyplot import show, subplots
  2. # make the twin Axes
  3. fig, ax0 = subplots()
  4. ax1 = ax0.twinx()
  5. # plot two lines in the 1st Axes, label them
  6. ax0.plot((0, 1, 2, 3, 4), color='g', label='green')
  7. ax0.plot((4, 3, 2, 1, 0), color='k', label='black')
  8. # make a scatter in the 2nd Axes, label it
  9. ax1.scatter(( 1, 2, 3),
  10. (41, 37, 23), color='r', label='red')
  11. # collect handles and labels in a list of lists [[h0, l0], [h1, l1]]
  12. handles_labels = [ax.get_legend_handles_labels() for ax in (ax0, ax1)]
  13. # but Axes.legend needs h=h0+h1 and l=l0+l1, so
  14. # ① transpose hl → [[h0, h1, [l0, l1]]
  15. hl_transposed = zip(*handles_labels)
  16. # ② sum the sub-lists in the list of handles and in the list of labels
  17. handles, labels = [sum(handles_or_labels, [])
  18. for handles_or_labels in hl_transposed]
  19. ax0.legend(handles, labels)
  20. show()
展开查看全部
of1yzvn4

of1yzvn42#

代码看起来基本正确,但在创建图例的方式上有一个小问题。您应该直接使用各个图中的句柄和标签创建图例,而不是将两个图例的句柄和标签组合在一起。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.dates as mdates
  4. from datetime import datetime, timedelta
  5. import pandas as pd
  6. # Assuming you have the time series data in numpy arrays named x_values, y_values, and fire_counts
  7. df = pd.read_csv('FireCountPenchMar2012.csv')
  8. print(df)
  9. xaxis = np.arange(0, 248, 1)
  10. yaxis = hdwi
  11. yaxis2 = df.fire_count
  12. print(yaxis2)
  13. # Step 1: Create the dates for the x-axis based on the starting date (1 March 00:00 UTC)
  14. start_date = datetime(2023, 3, 1, 0, 0, 0)
  15. dates = [start_date + timedelta(hours=3 * i) for i in range(len(xaxis))]
  16. plt.figure(figsize=(15, 10))
  17. # Step 2: Plot the first time series with dates on the x-axis
  18. line1, = plt.plot(dates, yaxis, 'o-g', label='HDWI')
  19. # Step 3: Format the first y-axis and add axis labels and a title
  20. plt.ylabel('HDW')
  21. plt.title('HDWI v/s Fire Counts')
  22. # Step 4: Create a second y-axis for the 'fire_counts' variable
  23. ax2 = plt.gca().twinx()
  24. line2, = ax2.plot(dates, yaxis2, 'o-r', label='Fire Counts')
  25. ax2.set_ylabel('Fire Counts')
  26. # Step 5: Create legends for both lines separately
  27. legend1 = plt.legend(handles=[line1], loc='upper left')
  28. legend2 = plt.legend(handles=[line2], loc='upper right')
  29. # Step 6: Add the legends to the plot
  30. plt.gca().add_artist(legend1)
  31. plt.gca().add_artist(legend2)
  32. # Step 7: Format the x-axis to display dates at regular intervals (e.g., every 2 days)
  33. date_format = mdates.DateFormatter('%b %d')
  34. plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=2))
  35. plt.gca().xaxis.set_major_formatter(date_format)
  36. # Step 8: Rotate the x-axis date labels for better readability
  37. plt.xticks(rotation=45)
  38. # Step 9: Adjust the layout and display the plot
  39. plt.grid()
  40. plt.tight_layout()
  41. plt.show()
展开查看全部

相关问题