Plotting: How to space xticks? - python

After aggregation, i plotted the numbers but iam struggling to space the xticks
Aggregation
tweet['Retweets']=pd.to_numeric(tweet['Retweets'])
tweet['Favorites']=pd.to_numeric(tweet['Favorites'])
sum_df = tweet.groupby(['Realdate'], as_index=False).agg({'Retweets': 'sum', 'Favorites': 'sum'})
sum_df=sum_df.reset_index()
Plotting
fig, ax1 = plt.subplots(figsize=(15, 10))
ax2 = ax1.twinx()
ax1.set_xlabel('Dates')
ax1.set_ylabel('Favorites', color='b')
ax2.set_ylabel('Retweets', color='b')
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()
sum_df['Favorites'].plot( kind='bar', color='y', ax=ax1)
sum_df['Retweets'].plot( kind='line', marker='d', ax=ax2)
ax1.legend(loc=2) # is this the right thing to do to place legends?
ax2.legend(loc=1) # is this the right thing to do to place legends?
ax1.set_xticklabels(sum_df.Realdate.values, rotation=90)
plt.title('Sum of Daily "Likes" and Retweets Time Series')
plt.show()
The resulting output
Can you please help me with the xticks spacing please? I tried several methods but no results.
Thanks very much

Related

Reverse vertical one of the subplots in python

I have two data frames to plot. One of bar chart, another one is a line chart.
I want to plot the barchart upside to down. (vertically reversed.)
How can i handle this?
fig, ax1 = plt.subplots(figsize=(10, 5))
tidy = results.melt(id_vars='Day').rename(columns=str.title)
ax1 = sns.lineplot(x='Day', y='Value', hue='Variable', data=tidy, ax=ax1)
tidy2 = drugs.melt(id_vars='Day').rename(columns=str.title)
ax1 = sns.barplot(x='Day', y='Value', hue='Variable', data=tidy2, ax=ax1)
ax1.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax1.legend(loc=1)
ax1.tick_params(axis='x', labelrotation=45)

Matplotlib view limit minimum is less than 1 with 2 different scales plot

I am trying to plot different pandas columns on two different scales, I took the example from the documentation but I am unsure about the error message. Here is my piece of code:
# Create some mock data
fig, ax1 = plt.subplots()
color = 'tab:red'
ax1.set_xlabel('Liquidity')
ax1.set_ylabel('Price', color=color)
ax1.plot(orderbooks_hedged['topBid'], color=color)
ax1.plot(orderbooks_hedged['topAsk'], color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx()
color = 'tab:blue'
ax2.set_ylabel('sin', color=color) # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.plot(orderbooks_hedged['topBidliquidity'], color=color)
ax2.plot(orderbooks_hedged['topAskliquidity'], color=color)
ax2.tick_params(axis='y', labelcolor=color)
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.show()
And my two different dataframe columns looks like the following:
topBid topAsk topBidliquidity topAskliquidity
ts
2020-06-15 09:00:07 4.145097 4.170428 24.715769 35039.309622
2020-06-15 09:00:08 4.145097 4.170428 4944.701928 35039.309622
2020-06-15 09:00:09 4.144620 4.170428 4944.701928 35039.309622
2020-06-15 09:00:10 4.144620 4.170428 4944.701928 35039.309622
And the error is the following:
ValueError: view limit minimum -36879.560332175926 is less than 1 and is an invalid Matplotlib date value
I tried to google it a bit but I did not had one specific answer for my issue. Can someone help me to understand my issue? thanks!
fig, ax1 = plt.subplots()
plt.figure(figsize=[15,10])
color_ask = 'tab:red'
color_bid = 'tab:blue'
ax1.set_xlabel('Liquidity')
ax1.set_ylabel('Price')
ax1.plot(orderbooks_hedged.index, orderbooks_hedged['topBid'], color=color_bid)
ax1.plot(orderbooks_hedged.index, orderbooks_hedged['topAsk'], color=color_ask)
ax1.tick_params(axis='y')
ax2 = ax1.twinx()
ax2.set_ylabel('liquidity') # we already handled the x-label with ax1
ax2.plot(orderbooks_hedged.index, orderbooks_hedged['topBidliquidity'], color=color_bid)
ax2.plot(orderbooks_hedged.index, orderbooks_hedged['topAskliquidity'], color=color_ask)
ax2.tick_params(axis='y')
fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.show()`enter code here`

Trying to plot 2 charts side-by-side, but one of them always comes out empty

I have two plots that I generated from my data:
Here the second plot shows the distribution of results from the first one.
What I want is to plot them side-by-side so you could see both the data and the distribution on the same plot. And I want plots to share y-axis as well.
I tried to do the following:
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(40, 15), sharey=True)
ax1 = sns.lineplot(plotting_df.index, plotting_df.error, color=('#e65400'), lw=2, label='random forest residual error')
ax1 = sns.lineplot(plotting_df.index, plotting_df.val, color=('#9b9b9b'), lw=1, label='current model residual error')
ax1 = sns.lineplot(plotting_df.index, 0, color=('#2293e3'), lw=1)
ax1.xaxis.set_visible(False)
ax1.set_ylabel('Residual Fe bias', fontsize=16)
ax1.set_title('Models residual error comparison', fontsize=20, fontweight='bold')
sns.despine(ax=ax1, top=True, bottom=True, right=True)
ax2 = sns.distplot(results_df.error, hist=True, color=('#e65400'), bins=81,
label='Random forest model', vertical=True)
ax2 = sns.distplot(plotting_df.val, hist=True, color=('#9b9b9b'),
bins=81, label='Rolling averages model', vertical=True)
ax2.set_title('Error distribution comparison between models', fontsize=20, fontweight='bold')
sns.despine(ax=ax2, top=True, right=True)
fig.savefig("blabla.png", format='png')
But when I do run it I get strange results - the first chart is in the second column, whereas I wanted it on the left and the second chart is completely blank. Not sure what I did wrong here.
Both lineplot and distplot accept a matplotlib axes object as an argument, which tells it which axes to plot onto. If no axes is passed into it, then the plot is placed onto the current axes.
You create a figure and 2 axes using :
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(40, 15), sharey=True)
Therefore, ax2 will be the current axes. So your distplot is being plotted on top of your lineplot, both in ax2.
You need to pass the axes into the seaborn plotting functions.
sns.lineplot(..., ax=ax1)
sns.distplot(..., ax=ax2)

Subplot date formatting in Axis

I have a 2x2 graph with date in x-axis in both graphs. I have used datetime.strptime to bring a string into type = datetime.datetime object format.
However I am planning to have some 12 subplots and doing this the following way seems messy.
Is there a better 'pythonic' way?
This is what I have:
xx.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
plt.grid(True)
plt.ylabel('paramA',fontsize=8, color = "blue")
plt.tick_params(axis='both', which='major', labelsize=8)
plt.plot(date_list, myarray[:,0], '-b', label='paramA')
plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment
xx = plt.subplot(2,1,2)
xx.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
plt.grid(True)
plt.ylabel('paramB', 'amount of virtual mem',fontsize=8, color = "blue")
plt.tick_params(axis='both', which='major', labelsize=8)
plt.plot(date_list, myarray[:,1], '-y', label='paramB')plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment ```
PS: Initially I tried defining the plot as follows. This however did not work:
fig, axs = plt.subplots(2,1,figsize=(15,15))
plt.title('My graph')
for ax in enumerate(axs):
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M:%S'))
You failed to provide any data or a Minimal, Complete, and Verifiable example. Nevertheless, something like this should work. You can extend it to your real case by using desired number of rows and columns in the first command.
fig, axes = plt.subplots(nrows=2, ncols=3)
labels = ['paramA', 'paramB', 'paramC', 'paramD', 'paramE', 'paramF']
for i, ax in enumerate(axes.flatten()):
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
ax.grid(True)
ax.set_ylabel(labels[i], fontsize=8, color="blue")
ax.tick_params(axis='both', which='major', labelsize=8)
ax.plot(date_list, myarray[:,i], '-b', label=labels[i])
plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment
EDIT:
Change your code to
fig, axs = plt.subplots(2,1,figsize=(15,15))
plt.title('My graph')
for ax in axs:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M:%S'))

How to add more stocks to a graph with twin axis's?

I have this code below to plt trends of stocks, and have 2 axis's one axis on the left and the other on right of the chart for 2 stocks with different scales. I can't figure out how I can add more stocks to the graph. I just have 2 stocks, but I like to add more.
How can I modify my code to add more stocks to the second axis?
fig, ax1 = plt.subplots()
fig = plt.figure(figsize=(6,4))
t = newdf['date']
s1 = newdf['IBM']
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('Dates', fontsize=14)
ax1.set_xticklabels(t, rotation=45)
ax1.legend(loc=0)
ax1.grid()
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('Price', color='b')
ax1.tick_params('y', colors='b')
ax2 = ax1.twinx()
s2 = newdf['AAPL']
ax2.plot(t, s2, 'r-')
ax2.set_ylabel('Price', color='r')
ax2.tick_params('date', colors='r', rotation=90)
ax2.legend(loc=2)
fig.tight_layout()
plt.show()
[
add more stocks just above fig.tight_layout() like this.
For nth stock add ax(n),s(n) and add stock name chose color from below link.
ax3 = ax1.twinx()
s3 = newdf[stock name]
ax3.plot(t, s3, 'r-')
ax3.set_ylabel('Price', color=your color)
ax3.tick_params('date', colors=your color, rotation=90)
ax3.legend(loc=3)
Color
RGB

Categories

Resources