Skip to content

time_plot: added snakecase and typehints #40#59

Open
Tanvi-Jain01 wants to merge 10 commits intosustainability-lab:masterfrom
Tanvi-Jain01:timeplot1
Open

time_plot: added snakecase and typehints #40#59
Tanvi-Jain01 wants to merge 10 commits intosustainability-lab:masterfrom
Tanvi-Jain01:timeplot1

Conversation

@Tanvi-Jain01
Copy link

This PR solves issue #40

@nipunbatra @patel-zeel

Before:

Code:

import numpy as np
import pandas as pd
np.random.seed(42)  

start_date = pd.to_datetime('2022-01-01')
end_date = pd.to_datetime('2022-12-31')

dates = pd.date_range(start_date, end_date)

pm25_values = np.random.rand(365)
ws_values = np.random.rand(365)
wd_values = np.random.rand(365)

df = pd.DataFrame({
    'date': dates,
    'pm25': pm25_values,
    'ws': ws_values,
    'wd': wd_values
})

df['date'] = df['date'].dt.strftime('%Y-%m-%d')  # Convert date format to 'YYYY-MM-DD'

print(df)

from vayu.timePlot import timePlot
axes=timePlot(df,'2022', 5)

Output:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[8], line 3
      1 from vayu.timePlot import timePlot
----> 3 axes=timePlot(df,'2022', 5)

File ~\anaconda3\lib\site-packages\vayu\timePlot.py:46, in timePlot(df, year, month, pollutants)
     43 color = color_list[ix % len(color_list)]
     45 # plotting
---> 46 plt.subplot(f"{len(pollutants)}1{ix}")
     47 a = values.plot.line(color=color)
     48 a.axes.get_xaxis().set_visible(False)

File ~\anaconda3\lib\site-packages\matplotlib\pyplot.py:1323, in subplot(*args, **kwargs)
   1320 fig = gcf()
   1322 # First, search for an existing subplot with a matching spec.
-> 1323 key = SubplotSpec._from_subplot_args(fig, args)
   1325 for ax in fig.axes:
   1326     # if we found an Axes at the position sort out if we can re-use it
   1327     if ax.get_subplotspec() == key:
   1328         # if the user passed no kwargs, re-use

File ~\anaconda3\lib\site-packages\matplotlib\gridspec.py:573, in SubplotSpec._from_subplot_args(figure, args)
    571     return arg
    572 elif not isinstance(arg, Integral):
--> 573     raise ValueError(
    574         f"Single argument to subplot must be a three-digit "
    575         f"integer, not {arg!r}")
    576 try:
    577     rows, cols, num = map(int, str(arg))

ValueError: Single argument to subplot must be a three-digit integer, not '510'
<Figure size 640x480 with 0 Axes>

AFTER:

Code:

import plotly.graph_objects as go

def time_plot(df:pd.DataFrame, year:str, pollutants:list=["pm25"]):
    # Cuts the df down to the month specified
    df.index = pd.to_datetime(df.date)
    df_n_1 = df[(df.index.month == int(month))]
    
    fig = go.Figure()
    
    for pollutant in pollutants:
        values = df_n_1[pollutant]
        
        # Add trace for each pollutant
        fig.add_trace(go.Scatter(
            x=values.index,
            y=values.values,
            name=pollutant
        ))
        
    # Configure layout
    fig.update_layout(
        xaxis=dict(
            rangeselector=dict(
                buttons=list([
                    dict(count=1, label="1d", step="day", stepmode="backward"),
                    dict(count=7, label="1w", step="day", stepmode="backward"),
                    dict(count=1, label="1m", step="month", stepmode="backward"),
                    dict(count=6, label="6m", step="month", stepmode="backward"),
                    dict(count=1, label="YTD", step="year", stepmode="backward"),
                    dict(count=1, label="1y", step="year", stepmode="backward"),
                    dict(step="all")
                ])
            ),
            rangeslider=dict(
                visible=True
            ),
            type="date"
        )
    )
    
    fig.show()
    

Usage:

time_plot(df, '2022',  pollutants=['pm25', 'pm10', 'no', 'no2', 'nox', 'nh3', 'so2', 'co', 'o3', 'benzene', 'toluene'])

Output:
timeplot plotly

@Tanvi-Jain01 Tanvi-Jain01 changed the title time_plot: added snakecase and typehints time_plot: added snakecase and typehints #40 Jul 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant