Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to handle times with a time zone in Matplotlib?
To handle times with a time zone in Matplotlib, we can use the pytz library along with Pandas datetime indexing. This approach ensures accurate timezone-aware plotting of time series data.
Steps to Handle Timezone Data
- Import required libraries: pandas, numpy, matplotlib, and pytz
- Create a DataFrame with timezone-aware datetime index using
pd.date_range() - Use
pytz.timezone()to specify the desired timezone - Plot the data using DataFrame's
plot()method - Display the figure using
plt.show()
Example
Here's how to create and plot timezone-aware data ?
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import pytz
plt.rcParams["figure.figsize"] = [10, 4]
plt.rcParams["figure.autolayout"] = True
# Create DataFrame with timezone-aware datetime index
df = pd.DataFrame(
dict(temperature=np.random.normal(25, 5, size=8)),
index=pd.date_range(
start='2024-03-11 01:30',
freq='2H',
periods=8,
tz=pytz.timezone('US/Eastern')))
print("DataFrame with timezone:")
print(df)
print(f"\nTimezone: {df.index.tz}")
# Plot the data
df.plot(marker='o', linewidth=2)
plt.title('Temperature Data with US/Eastern Timezone')
plt.ylabel('Temperature (°C)')
plt.grid(True, alpha=0.3)
plt.show()
DataFrame with timezone:
temperature
2024-03-11 01:30:00-04:00 24.234567
2024-03-11 03:30:00-04:00 28.891234
2024-03-11 05:30:00-04:00 22.567890
2024-03-11 07:30:00-04:00 26.123456
2024-03-11 09:30:00-04:00 21.789012
2024-03-11 11:30:00-04:00 29.345678
2024-03-11 13:30:00-04:00 23.901234
2024-03-11 15:30:00-04:00 27.456789
Timezone: US/Eastern
Converting Between Timezones
You can convert timezone-aware data to different timezones using tz_convert() ?
import pandas as pd
import numpy as np
import pytz
from matplotlib import pyplot as plt
# Create data in UTC
utc_data = pd.DataFrame(
dict(value=np.random.normal(100, 10, size=6)),
index=pd.date_range(
start='2024-01-01 12:00',
freq='4H',
periods=6,
tz=pytz.UTC))
# Convert to different timezones
eastern_data = utc_data.tz_convert('US/Eastern')
pacific_data = utc_data.tz_convert('US/Pacific')
print("Original UTC data:")
print(utc_data.index)
print("\nConverted to US/Eastern:")
print(eastern_data.index)
Original UTC data:
DatetimeIndex(['2024-01-01 12:00:00+00:00', '2024-01-01 16:00:00+00:00',
'2024-01-01 20:00:00+00:00', '2024-01-02 00:00:00+00:00',
'2024-01-02 04:00:00+00:00', '2024-01-02 08:00:00+00:00'],
dtype='datetime64[ns, UTC]', freq='4H')
Converted to US/Eastern:
DatetimeIndex(['2024-01-01 07:00:00-05:00', '2024-01-01 11:00:00-05:00',
'2024-01-01 15:00:00-05:00', '2024-01-01 19:00:00-05:00',
'2024-01-01 23:00:00-05:00', '2024-01-02 03:00:00-05:00'],
dtype='datetime64[ns, US/Eastern]', freq='4H')
Common Timezone Operations
| Operation | Method | Description |
|---|---|---|
| Create timezone-aware | pd.date_range(tz='UTC') |
Creates datetime index with timezone |
| Convert timezone | tz_convert('US/Pacific') |
Converts to different timezone |
| Remove timezone | tz_localize(None) |
Converts to naive datetime |
Conclusion
Use pytz.timezone() with Pandas date_range() to create timezone-aware data for Matplotlib plotting. This ensures accurate time representation across different geographic regions and handles daylight saving time automatically.
Advertisements
