numpy 在matplotlib中使用twinx()绘图时如何正确添加图例?

tvz2xvvm  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(133)

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

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta

# Assuming you have the time series data in numpy arrays named x_values, y_values, and fire_counts
df=pd.read_csv('FireCountPenchMar2012.csv')
print(df)

xaxis=np.arange(0,248,1)
yaxis=hdwi
yaxis2=df.fire_count
print(yaxis2)

# Step 1: Create the dates for the x-axis based on the starting date (1 March 00:00 UTC)
start_date = datetime(2023, 3, 1, 0, 0, 0)
dates = [start_date + timedelta(hours=3*i) for i in range(len(xaxis))]

plt.figure(figsize=(15,10))

# Step 2: Plot the first time series with dates on the x-axis
plt.plot(dates, yaxis, 'o-g', label='HDWI')

# Step 3: Format the first y-axis and add axis labels and a title
plt.ylabel('HDW')
plt.title('HDWI v/s Fire Counts')

# Step 4: Create a second y-axis for the 'fire_counts' variable
ax2 = plt.gca().twinx()
ax2.scatter(dates, yaxis2, color='red', label='Fire Counts')
ax2.set_ylabel('Fire Counts')

# Step 5: Show the legend for both lines (y_values and fire_counts)
lines, labels = plt.gca().get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()

# Combine the handles and labels for both legends
all_lines = lines + lines2
all_labels = labels + labels2

# Display the combined legend
plt.gca().legend(all_lines, all_labels)

# Step 6: Format the x-axis to display dates at regular intervals (e.g., every 2 days)
date_format = mdates.DateFormatter('%b %d')
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=2))
plt.gca().xaxis.set_major_formatter(date_format)

# Step 7: Rotate the x-axis date labels for better readability
plt.xticks(rotation=45)

# Step 8: Adjust the layout and display the plot
plt.grid()
plt.tight_layout()
plt.show()here

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

798qvoo8

798qvoo81#

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

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta
import pandas as pd

# Assuming you have the time series data in numpy arrays named x_values, y_values, and fire_counts
df = pd.read_csv('FireCountPenchMar2012.csv')
print(df)

xaxis = np.arange(0, 248, 1)
yaxis = hdwi
yaxis2 = df.fire_count
print(yaxis2)

# Step 1: Create the dates for the x-axis based on the starting date (1 March 00:00 UTC)
start_date = datetime(2023, 3, 1, 0, 0, 0)
dates = [start_date + timedelta(hours=3 * i) for i in range(len(xaxis))]

plt.figure(figsize=(15, 10))

# Step 2: Plot the first time series with dates on the x-axis
plt.plot(dates, yaxis, 'o-g', label='HDWI')

# Step 3: Format the first y-axis and add axis labels and a title
plt.ylabel('HDW')
plt.title('HDWI v/s Fire Counts')

# Step 4: Create a second y-axis for the 'fire_counts' variable
ax2 = plt.gca().twinx()
ax2.scatter(dates, yaxis2, color='red', label='Fire Counts')
ax2.set_ylabel('Fire Counts')

# Step 5: Show the legend for both lines (y_values and fire_counts)
plt.legend()

# Step 6: Format the x-axis to display dates at regular intervals (e.g., every 2 days)
date_format = mdates.DateFormatter('%b %d')
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=2))
plt.gca().xaxis.set_major_formatter(date_format)

# Step 7: Rotate the x-axis date labels for better readability
plt.xticks(rotation=45)

# Step 8: Adjust the layout and display the plot
plt.grid()
plt.tight_layout()
plt.show()

字符串

相关问题