Proper visualization of the label name [duplicate] - python

This question already has answers here:
Rotate axis text in python matplotlib
(13 answers)
How to rotate x-axis tick labels in a pandas plot
(5 answers)
Closed 1 year ago.
How can I properly structure the label name of the generated graph? The code used in generating the graph is written below:
from sklearn.feature_selection import mutual_info_classif
plt.figure(figsize=(20,5))
feat_import = pd.Series(importance, new_data.columns[0:len(new_data.columns)-2])
plt.plot(feat_import, 'r')
plt.title('Best Feature Selection')
plt.ylabel('Importance')
plt.xlabel('Available features')
plt.legend([ 'importance to dependent variable'], loc='upper right')
The generated result is this:
I underlined with green color where I am having the issue.
One of the best ways will be to show the label name vertically rather than the horizontal display shown above. Please, how can I achieve that?

Rotating the label names of the horizontal axis can be done via:
plt.xticks(rotation = 90) # Rotates X-Axis Ticks by 90-degrees
Minimal example:
import matplotlib.pyplot as plt
import pandas as pd
plt.figure(figsize=(6,6))
feat_import = pd.Series(data=range(10), index=['abc' * (i+1) for i in range(10)])
plt.plot(feat_import, 'r')
plt.xticks(rotation=90)
plt.show()

Related

X axis for plt plot python is cluttered together [duplicate]

This question already has answers here:
Matplotlib showing x-tick labels overlapping
(3 answers)
Closed 11 months ago.
plt.figure(figsize=(4,4))
aapl_data.plot.line(x='Date',y='Adj Close',title='test')
plt.ylabel('Adj Close')plt.show()
How do i declutter the X axis. I tried using figsize in the code but it does not do anything
Better show the whole code. Since I'm not sure if you have such a string: ax = plt.axes()
ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))
Try to formate the date
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
There can be two solutions to this problem.
Increasing the width of the window. This can be achieved by:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(40,4))
fig.add_subplot(1,1,1).plot([1,2,3], [1,2,3])
plt.show()
Making the labels vertical rather than horizontal. This can be done by:
plt.xticks(range(10), rotation='vertical')

Emphasize on line of the grid with Seaborn [duplicate]

This question already has answers here:
Plot a horizontal line on a given plot
(7 answers)
Closed 1 year ago.
I am using Seaborn to plot a violin graph (as you can see on the pic below):
I would like to emphasize the line at the 0 level on the y-axis (Comparison_perc) and then make it slightly bigger/darker.
Would you know how?
Many thanks,
Guillaume
I believe you can add a horizontal line using axhline() e.g.
#Import libraries
import seaborn as sns
import matplotlib.pyplot as plt
#Load example dataset
dataset = sns.load_dataset("iris")
#Create graph
graph = sns.barplot(x="sepal_width", y="petal_width", data=dataset)
#Draw a horizontal line at 0
graph.axhline(y=0)
#Show plot
plt.show()
And you can change the color/thickness etc, e.g. graph.axhline(y=0, linewidth=4, color='r')

How to plot y-axis to the opposite side? [duplicate]

This question already has answers here:
matplotlib y-axis label on right side
(4 answers)
Closed 2 years ago.
I have this chart below:
I would want the y-axis for the lower subplot to be plotted to the opposite side since that would make more sense. Is there a method for this? The ax.invert_yaxis() simply inverts the labels.
Note: For the curious, I simply used .invert_xaxis() to plot inverted bars.
I guess, what you are looking for is
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
of an axis object.
So with #meTchaikovsky's MVE code, you'll get
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(1,10,10)
y0 = np.random.randint(0,30,size=10)
fig,ax = plt.subplots(nrows=2,ncols=1,figsize=(8,6))
ax[1].set_xlim(0,30)
ax[0].barh(x,y0,color='violet')
ax[0].set_ylabel("Y-Axis")
ax[1].set_xlim(30,0)
ax[1].barh(x,y0,color='deepskyblue')
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
ax[1].set_ylabel("Y-Axis")
plt.show()

matplotlib: place legend labels where each trace intercepts the right-hand y-axis [duplicate]

This question already has answers here:
How to annotate end of lines using python and matplotlib?
(3 answers)
Closed 3 years ago.
I have multiple lines plotted on an xy scatter plot
There are more than the number of colours in my palette, which means the colours start cycling.
I have played with using other palettes but the visibility suffers.
An idea I would like to explore now is to add the legend labels at the point where each line intercepts the right-hand y-axis.
Something like this:
Is this possible to achieve with matplotlib and/or seaborn?
Quick one, with use of the other answer to this question
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
names = ['foo', 'bar', 'foobar']
N_size = 100
fig, ax = plt.subplots(1, 1)
df = pd.DataFrame(map(lambda x: pd.Series(np.cumsum(np.random.rand(N_size) - 0.5), name=x), names)).T
df.plot(ax=ax)
ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())
ax2.set_yticks([df[col].iloc[-1] for col in df.columns])
ax2.set_yticklabels(df.columns)
plt.show()

Moving all x-axis tick labels a few pixels to the right (aligning rotated labels) [duplicate]

This question already has an answer here:
Moving matplotlib xticklabels by pixel value
(1 answer)
Closed 5 years ago.
I'm doing a bar plot with long labels, which I've rotated 45 degrees and set to be right-aligned. However, the tick labels are still a bit away from the ticks, making the plot look strange. How do move all the labels a few points to the right?
Here is my current code:
import seaborn as sns
import pylab as plt
plt.figure()
ax = sns.barplot(x="item", y="dist", hue="dset", data=df)
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
EDIT: Please take look at the right-aligned subplot in stackoverflow.com/a/14854007/1452257 for an example. I can also copy the code/image to this post if you prefer.
From ImportanceOfBeingErnest's answer here, I got the following on translating tick labels in a general, arbitrary way:
import matplotlib.transforms as mtrans
# ...
trans = mtrans.Affine2D().translate(20, 0)
for t in ax.get_xticklabels():
t.set_transform(t.get_transform()+trans)

Categories