简体   繁体   中英

How to align y and x axis using matplotlib

I am starting Python and I would like to use pandas and matplotlib to trace plots. I am using this code:

import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.dates import AutoDateLocator

plt.style.use('ggplot')

nbColonnes = list(range(0, 15))
monCSV = pd.read_csv('DUT_1_SS1#24.csv', names=nbColonnes, encoding='latin1', skiprows=5)

monCSV.loc[-1] = ['No:', 'Time', 'DUT_Mode', 'Probe of Humidity (%)', 'Probe of Temperature (°C)', 'Timestamp',
                  'Voltage (V)', 'Timestamp', 'Current (A)', 'Timestamp', 'CAN_State', 'Timestamp', 'Touch Status',
                  'Timestamp', 'Reset Counter']  # adding a row
monCSV.index = monCSV.index + 1  # shifting index
monCSV.sort_index(inplace=True)

monCSV.columns = monCSV.iloc[0]  

wake_mode = monCSV[monCSV.DUT_Mode != 'Sleep Mode'] 
wake_current = wake_mode.iloc[1:, 8]

# pour changer le format de la date
time = pd.to_datetime(monCSV.iloc[1:610, 1], errors='coerce').dt.strftime('%H:%M')

wake_time = pd.to_datetime(wake_mode.iloc[1:, 1], errors='coerce').dt.strftime('%H:%M')

# on définit les colonnes à tracer 
date = monCSV.iloc[:, 1]  
temperature = monCSV.iloc[1:610, 4]  
current = monCSV.iloc[1:610:, 8]

xtick_locator = AutoDateLocator()

fig, ax1 = plt.subplots()
ax1.xaxis.set_major_locator(xtick_locator)
ax1.xaxis.set_major_locator(plt.MaxNLocator(7))

color1 = 'tab:blue'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('Current (A)', color=color1)
ax1.scatter(wake_time, wake_current, color=color1)
ax1.tick_params(axis='y', labelcolor=color1)

ax2 = ax1.twinx()  
ax2.xaxis.set_major_locator(xtick_locator)
ax2.xaxis.set_major_locator(plt.MaxNLocator(7))
color2 = 'tab:red'
ax2.set_ylabel('Temperature (°C)', color=color2)  # we already handled the x-label with ax1
ax2.plot(time, temperature, color=color2)
ax2.tick_params(axis='y', labelcolor=color2, grid_alpha=0, direction='in',
                length=5, width=1.5, colors=color2)

#plt.xticks(rotation=30)
fig.tight_layout()  

# plt.show()
plt.savefig('temperature.png', dpi=400, bbox_inches='tight')

and I get this plot:

电流输出图

I am trying to plot 2 data using the secondary y axis and that share the same x-axis. I noticed that blue points are not at the right place as we can see with Excel plot:

所需的输出图

Could you help me please? Feel free to tell me if you have any advice to improve my code.

Download CSV file

Your time and wake_time are being converted from datetime format to string format. If you keep them as datetime you will get the following output:

matplotlib 截图

Try the following:

time = pd.to_datetime(monCSV.iloc[1:610, 1], errors='coerce') #.dt.strftime('%H:%M')
wake_time = pd.to_datetime(wake_mode.iloc[1:, 1], errors='coerce') #.dt.strftime('%H:%M')

You can then tell matplotlib where to locate ticks on the timeline using a date locator. In your case HourLocator() .

import pandas as pd
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.dates as mdates

plt.style.use('ggplot')

nbColonnes = list(range(0, 15))
monCSV = pd.read_csv('DUT_1_SS1#24.csv', names=nbColonnes, encoding='latin1', skiprows=5)

monCSV.loc[-1] = ['No:', 'Time', 'DUT_Mode', 'Probe of Humidity (%)', 'Probe of Temperature (°C)', 'Timestamp',
                  'Voltage (V)', 'Timestamp', 'Current (A)', 'Timestamp', 'CAN_State', 'Timestamp', 'Touch Status',
                  'Timestamp', 'Reset Counter']  # adding a row
monCSV.index = monCSV.index + 1  # shifting index
monCSV.sort_index(inplace=True)

monCSV.columns = monCSV.iloc[0]  

wake_mode = monCSV[monCSV.DUT_Mode != 'Sleep Mode'] 
wake_current = wake_mode.iloc[1:, 8]

# pour changer le format de la date
time = pd.to_datetime(monCSV.iloc[1:610, 1], errors='coerce') #.dt.strftime('%H:%M')
wake_time = pd.to_datetime(wake_mode.iloc[1:, 1], errors='coerce') #.dt.strftime('%H:%M')

# on définit les colonnes à tracer 
date = monCSV.iloc[:, 1]  
temperature = monCSV.iloc[1:610, 4]  
current = monCSV.iloc[1:610:, 8]

fig, ax1 = plt.subplots()
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
ax1.xaxis.set_major_locator(matplotlib.dates.HourLocator())

color1 = 'tab:blue'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('Current (A)', color=color1)
ax1.scatter(wake_time, wake_current, color=color1)
ax1.tick_params(axis='y', labelcolor=color1)

ax2 = ax1.twinx()  
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
ax2.xaxis.set_major_locator(matplotlib.dates.HourLocator())

color2 = 'tab:red'
ax2.set_ylabel('Temperature (°C)', color=color2)  # we already handled the x-label with ax1
ax2.plot(time, temperature, color=color2)
ax2.tick_params(axis='y', labelcolor=color2, grid_alpha=0, direction='in', length=5, width=1.5, colors=color2)

#plt.xticks(rotation=30)
fig.tight_layout()  

plt.show()
plt.savefig('temperature.png', dpi=400, bbox_inches='tight')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM