Fixing OverLap of "x" Axis values in a ScatterPlot - MatPlotLib - python

Hi,
How can I increase the "x" axis spread (by the appropriate python code) of the scatter plot so that each region label (Europe, S.Asia etc. etc.) will not over lap with each other as shown.
Please advice.
Have been struggling with it for quite some while.
Thanks

Consider rotating the labels with:
plt.xticks(rotation=90)
or increase figure size using:
fig = plt.scatter(...)
fig.set_size_inches(18.5, 10.5)

Related

How set a specific range of x-axis and increase the length of the plot?

I´m looking to add a specific range of values to the x-axis of my plot and increase the length of this axis.
I change the range of the values of my x-axis; however, the values keep in a specific range.
Besides, I tried to increase the length of the x-axis but I failed again.
For now, I´m only plotting an empty graph, because a need to set the specifications for the axis.
Here is part of the code to the plot:
fig1, ax = plt.subplots()
ax.set_xlim(1, 1200)
ax.set_ylim(-800, 200)
ax.set_box_aspect(1)
plt.show()
This code gives me a plot square with the range of the:
x-axis = 0-200-400...1200,
I´m looking for:
x-axis = 0-50-100-150...1200
Also, I need to change the shape of the plot: square to a rectangular, where the x-axis increases the length.
Any suggestion or comment is welcome!
Thank!
plt.figure(figsize=(15,2))
Use this at first line to set the size of your plot. As you want to increase x-axis, then see that x>y in figsize parameter.
l1=np.arange(0,1250,50)
plt.xticks(l1)
Use the above code after setting y limits to set the xticks in range of 0-1200 with gap of 50.
``
You can change the size (and therefore the shape) of a pyplot figure like this:
fig1.set_size_inches(10, 8)
As for the ticks on the axis, this post gives a pretty in-depth answer on how to customize those.

How to show all the labels in matplotlib?

I am trying to display a chart using matplotlib. But my labels are so big that they are overlapping each other. I want to show it cleanly no overlapping. How can I do that? I am now using below code:
import matplotlib.pyplot as plt
x = ['jdwdw723#gmail.com' ,'emcast.test10#gmail.com', 'pbChinaTester#clp.com']
y = [10,25,6]
plt.plot(x,y)
plt.xlabel("loginId")
plt.ylabel("times appeared in the data")
plt.title("loginId Graph")
plt.tight_layout()
plt.show()
I tried your example code, and it doesn't seem to be overlapping there. There are many possibilities. One, commonly used, is to rotate the labels.
You can do it like this:
plt.xticks(rotation=45)
There are more ideas in Changing the “tick frequency” on x or y axis in matplotlib? and in reducing number of plot ticks.
I created an example notebook here, feel free to duplicate and play with it.

When using external axes method to plot multiple candlestick charts using mplfinance library, how to plot volume inside the candlestick chart?

The project I am doing requires code to plot more than 300 candlestick charts in several figures using mplfinance library. I am aware that this can only be done using external axes method as it provides more flexibilities and can plot unlimited charts theoretically.
The current code I am using is as below, the charts plotted can be seen below:
import mplfinance as mpf
s = mpf.make_mpf_style(base_mpf_style='yahoo', rc={'font.size': 6})
fig = mpf.figure(figsize=(34, 13.2), style=s, tight_layout=True)
ax_p = fig.add_subplot(n_rows, n_cols, pos_price)
ax_v = fig.add_subplot(n_rows, n_cols, pos_vol, sharex=ax_p)
fig, ax_list = mpf.plot(resampled_df, type='candle', ax=ax_p, volume=ax_v, show_nontrading=False,
datetime_format='%a %d-%m-%y', xrotation=0, returnfig=True)
The screenshot of the 6 sample charts from hundreds of charts my code plotted:
The screenshot of the two charts the above code plotted is as below:
As you can see the volume chart was plotted in an individual chart below the candlestick chart. I struggle to find the solution to move the volume into candlestick chart, there is a similar post in mplfinance documentation issue 114 kind of explains how to do this...... but I found it is rather difficult to understand for new ppl to the library like me.
Would highly appreciate it if you could post the detailed code to do this!
Update on 12th Feb 2021:
I modified the code with #Daniel's suggestion, use add_axes() rather than add_subplot() and now the volume is at the bottom of the candlestick chart when plotting multiple charts. Beautiful! Answer accepted.
ax_intra_day_candle = fig.add_axes([x_pos, y_pos, ax_width, ax_height])
ax_intra_day_candle.set_title(title)
ax_intra_day_volume = fig.add_axes([x_pos, y_pos - ax_vol_height, ax_width, ax_vol_height], sharex=ax_intra_day_candle)
mpf.plot(intra_day_df, type='candle', ax=ax_intra_day_candle, volume=ax_intra_day_volume, show_nontrading=False,
datetime_format='%a %m-%d', xrotation=0)
I will assume what you are asking is to have the volume and candlesticks share the same x-axis similar to this image here.
The simplest way to do this is to use fig.add_axes() (instead of fig.add_subplot())
In this way you can control exactly where in the Figure each Axes is placed. You can see this being done in the mplfinance code here.
The basic idea is that you specify the location of each Axes object in terms of a fraction of the total figure, indicating the lower left corner of the Axes, and its width and height.
When you want two Axes objects to touch, with no space between them, you specify the location and width/height accordingly so that the top of the lower Axes and the bottom of the upper Axes exactly meet.
So, for example, to stack two equally sized Axes exactly on top of each other, lets say in the upper left quadrant of the Figure you would have:
# ax = fig.add_axes([left,bottom,width,height])
ax1 = fig.add_axes([0.05,0.75,0.5,0.25])
ax2 = fig.add_axes([0.05,0.50,0.5,0.25])
The 0.05 space to the left allows room for the y-axis labels.
ax1 starts three quarters (0.75) of the way up from the bottom, and stretches half way (0.5) to the right with a height of 0.25 (which takes it to the very top of the Figure).
ax2 starts half way (0.50) up from the bottom, also stretches half way (0.5) across to the right, and has a height of 0.25 taking it exactly to the very bottom of ax1.
HTH
Here is a more specific example, and the result. Notice how the candles and volume plot together only take up the upper left quadrant of the figure:
fig = mpf.figure(figsize=(8,8),style='yahoo')
ax1 = fig.add_axes([0.05,0.75,0.5,0.25])
ax2 = fig.add_axes([0.05,0.50,0.5,0.25])
mpf.plot(df,type='candle',ax=ax1,volume=ax2)
mpf.show()
No need so long code use the below code
suppose you have volume and data for plotting in a chart using mplfinance
mpf.plot(data,type='candle',style='yahoo',volume=True)

How to switch direction of axis in 3D scatterplot plotly?

I plotted the following using plotly and got the resulting plot shown before. X is the # of hours in a day, Y is a proportion between 0-1, and Z is a categorical variable with levels {0,1,2}.
However, it's unclear why the X seems to be going the opposite direction of what we're used to with a 3D Cartesian place where it's down(-) and up(+), left(-) and right(+), and front(-) and back(+). However, X seems to decrease from front to back instead of increase. I am new to plotly and am not sure how to flip the axis so it goes from 0 to 1 instead of 1 to 0. I would greatly appreciate help on this!
fig = px.scatter_3d(X_combined, x='x', y='y', z='z',
color='set', symbol='predictions', opacity=0.7)
fig.update_traces(marker=dict(size=12,
line=dict(width=5,
color='Black')),
selector=dict(mode='markers'))
For 3D plots, the options for axes are under layout.scene.
The autorange option is therefore located under layout.scene.xaxis.autorange and can be modified like this:
fig.update_scenes(xaxis_autorange="reversed")
References:
python/3d-axes
python/layout-scene-xaxis-autorange
This should do the trick:
fig.update_xaxes(autorange="reversed")
Alternatively, you can reverse it with a specific range:
fig.update_xaxes(range=[9, 3])

L-shaped Gridspec using matplotlib gs.update

This one is a quick and easy one for the matplotlib community. I was looking to plot an L-shaped gridspec layout, which I have done:
Ignoring a few layout issues I have for the moment, what I have is that the x-axis in the gs[0] plot (top left) shares the x-axis with the gs[2] plot (bottom left) and the gs[2] shares its y axis with the gs[3] plot. Now, what I was hoping to do was update the w-space and h-space to be tighter. So that the axes are almost touching, so perhaps wspace=0.02, hspace=0.02 or something similar.
I was also hoping that the bottom right hand plot was to be longer in the horizontal orientation, keeping the two left hand plots square in shape. Or as close to square as possible. If someone could run through all of the parameters I would be very appreciative. I can tinker then in my own time.
To change the spacings of the plot with grid spec:
gs = gridspec.GridSpec(2, 2,width_ratios=[1,1.5],height_ratios=[1,1])
This changes the relative size of plot gs[0] and gs[2] to gs1 and gs[3], whereas something like:
gs = gridspec.GridSpec(2, 2,width_ratios=[1,1],height_ratios=[1,2])
will change the relative sizes of plot gs[0] and gs1 to gs[2] and gs[3].
The following will tighten up the plots:
gs.update(hspace=0.01, wspace=0.01)
This gave me the following plot:
I also used the following to remove the axis labels where needed:
nullfmt = plt.NullFormatter()
ax.yaxis.set_major_formatter(nullfmt)
ax.xaxis.set_major_formatter(nullfmt)

Categories

Resources