Fixing labels of a 6 x 6 graph [duplicate] - python

This question already has answers here:
Improve subplot size/spacing with many subplots
(8 answers)
Closed 1 year ago.
Hi I'm very new to Python, and I'm trying to fix the labels because they overlap, (as seen in the picture). I figured the hspace and the wspace is the columns, but I'm not sure exactly how to adjust everything else in the labels, I don't want to mess with the x axis. Is there a way to make this plot look clearer?
Here's what I have:
_, axes = plt.subplots(nrows=6, ncols=6, sharex=True)
plt.suptitle('mean activity duration by time of day')
plt.subplots_adjust(hspace=0.5, wspace=0.5)
for ax, (activity, df) in zip(axes.ravel(), df_all.groupby('e')):
(df.groupby('f')
.d
.mean()
.plot(ax=ax,
kind='bar',
title=activity,
xlabel='time'))
6 x 6 bar graph:

Use constrained_layout.
use a larger figure size so your titles are not larger than your axes
use a smaller font size for the titles.
You can use tight_layout if you prefer, but constrained_layout is more flexible.

You can try to use plt.tight_layout, adjusts subplot params so that the subplot(s) fits in to the figure area

Related

X-axis labels are overlapping when plotting dataframe [duplicate]

This question already has answers here:
matplotlib xticks labels overlap
(1 answer)
How to prevent x-axis labels from overlapping
(4 answers)
Closed 1 year ago.
I have 115 columns, I want to plot the column names on the x-axis. But the column names are overlapping with each other. The y-axis has single row values.
features = fdf.iloc[0] # single row
features.sort_values(ascending=False).plot(kind='bar')
plt.xticks(rotation=90)
plt.show()
This is the graph, as you can see that the x-axis labels are not clear.
You have few options :
make the figure wider using figsize argument in plot
features.sort_values(ascending=False).plot(kind='bar', figsize = (15, 7))
Reduce the size of xticks label on x axis using fontsize argument in `xticks'
plt.xticks(rotation=90, fontsize = 'xx-small')
read about more options for fontsize here

partially visible spine matplotlib [duplicate]

This question already has an answer here:
Changing the length of axis lines in matplotlib
(1 answer)
Closed 1 year ago.
I am interested in creating a plot where only part of the spine is visible (say only for positive values), while the plot is shown for both negative and positive values.
set_position # seems to only set the point where it intersects with the other axis
set_visible # is an on-off switch. It does not allow for partial visibility.
Is there a way to do this?
With ax as the axes, if the x-axis is to show only between 0 and 0.5, then:
ax.spines['bottom'].set_bounds((0, 0.5))
You might need to set the ticks, as well, so, for instance:
ax.set_xticks([0, 0.25, 0.5])

adding secondry y-axis in python line plot [duplicate]

This question already has answers here:
secondary_y=True changes x axis in pandas
(2 answers)
Plot multiple Y axes
(3 answers)
Closed 4 years ago.
I want to add secondary y-axis. I have my data in CSV with three column date, lscc and cc. I want to add LSCC as first y-axis and CC as secondry. so far I have done this
df=pd.read_csv("E29Lsccvalue.csv", index_col='Date' )
plt.ylabel("")
plt.xlabel("Low level Similarity Class Cohesion (LSCC) Evolution")
df.plot(kind="line", marker='o',legend=None)
plt.xticks(rotation=90)
plt.show()
thanks
Within matplotlib I have used twinx() when I want to utilize the existing X-axis I have created, yet plot more data on top with a different Y axis. In your case with df as the first plot object:
axCC = df.twinx() # second axis sharing the same X axis of the original
Then you can include plots, labels, and other parameters referenced to this axis through calls such as:
axCC.set_ylabel("ExampleLabel",color="tab:red")
axCC.plot(xData,yData,color="blue")
Etc, etc.
A fully functional example with more detail is shown here
Although no reproducible date is provided, I guess you can achieve the desired result by doing this:
ax = df.plot(secondary_y='CC')
eventually adding all your ax customization required
edit: dotted line customization
Suppose you need a dotted vertical line at a certain position on your x-axis (in this example, at position 2 from your pandas index), use axvline and ':' as linestyle (dots)
ax = a.plot(secondary_y='Price')
ax.axvline(a.index.values[2], linestyle=':')

How to display a legend below graph without changing the figure size in matplotlib [duplicate]

This question already has answers here:
Creating figure with exact size and no padding (and legend outside the axes)
(2 answers)
How to put the legend outside the plot
(18 answers)
Closed 4 years ago.
I am trying to put a legend below a graph but keeping the figure size fixed.
Is this possible?
I saw How to put the legend out of matplotlib plot and https://stackoverflow.com/a/4701285/7746941 but the first one does not address fitting the legend within a predefined figure size while the second one does not do this generically (there is an example where the axes width is shrunk by 0.8 to accommodate the legend) .
Below is my current solution that anchors the legend at the bottom of the graph but the legend does not fit the figure.
I cannot figure out how to determine the height of the legend box to move the axis up by that amount.
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
ax = df.plot(figsize=(4,4))
tight_box = ax.transAxes.inverted().transform(ax.get_tightbbox(ax.figure.canvas.get_renderer()))
leg = ax.legend(bbox_to_anchor=(0,tight_box[0][1],1,0), loc='upper center')

Python - Plot values in different color [duplicate]

This question already has answers here:
How to plot one line in different colors
(5 answers)
Closed 6 years ago.
I am new to matplotlib and I need to plot on the same figure a large amount of data. My initial code is
data = np.genfromtxt('Data.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['CSX', 'CSY'])
fig = plt.figure()
myPlot = fig.add_subplot(111)
myPlot.plot(data['CSX'], data['CSY'], color='r', label='the data')
leg = myPlot.legend()
plt.show()
The result is acceptable, I need though to have two different colors on these data, based on a third value. Could you point me to the correct direction? Thanks!
Filter your data into 2 or more sets based on some value/condition and just call plot for each set of data with different colour values.

Categories