I have been able to change the facecolor of a plot using basic colors, r,g,b etc. However, I am working on a project and I need to prepare a presentation that will be visually pleasing and I would like to use a wider range of colors, such as colors that are listed here. This is the code I am using (I want the area below the graph to be colored):
fig = plt.figure(num=None, figsize=(30, 50))
ax1 = fig.add_subplot(2,1,1)
ax1.plot(x, y, 'k-')
ax1.fill_between(x, min(y), y, facecolor='#8B0000')
However, facecolor does nothing when I use HEX colors, but it works when I use 'r','b' etc. Is there any way to use HEX color codes for fill_between?
According the docs facecolor accepts matplotlib color arg or sequence of rgba tuples. If you want to use hex colors you must first convert the hex value to correct format. Take a look at the matplotlib.colors module. I'm not fully familiar with the library but maybe hex2color is of use.
Related
I am looking through the matplotlib api and can't seem to find a way to change the space between legend markers. I came across a way to change the space between a marker and its respective handle with handletextpad, but I want to change the space between each marker.
Ideally, I'd like to have the markers touching eachother with the labels above (or on top of) the markers.
My legend:
What I am trying to model:
Is there a way to do this?
I am not sure if this matches your expectations. We have used the standard features to create a graph that is similar to your objectives. Since the code and data are unknown to me, I customized the example in the official reference to create it, using handletextpad and columnspacing, and since the numbers are in font units, I achieved this with a negative value.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
fig, ax = plt.subplots(figsize=(8,8))
for color in ['tab:blue', 'tab:orange', 'tab:green']:
n = 750
x, y = np.random.rand(2, n)
scale = 200.0 * np.random.rand(n)
ax.scatter(x, y, c=color, s=scale, label=color.split(':')[1][0],
alpha=0.5, edgecolors='none')
handlers, labels = ax.get_legend_handles_labels()
print(labels)
ax.legend(handletextpad=-1.2, columnspacing=-0.5, ncol=3,loc="upper left", bbox_to_anchor=(0.75, 1.08))
ax.grid(True)
plt.show()
Currently I'm working on a university bioinformatics project. I have plot with an axis where values should be in italic format (Proteobacteria, Bacteroidata, etc should be in italic), but I can't find any solution how to change format ONLY for one axis values. I have found that using plt.rcParams.update() function can help, but it changes all plot/graph to italic format, but as I said I only need to change only one axis.
My code:
color_map = ['#dfdfdf' for i in range(len(order_count))]
color_map[0] = '#e81518'
fig, ax = plt.subplots(1,1, figsize=(13,7))
ax.barh(phyl_count['Phylum'], phyl_count['Phyl_Perc'], linewidth=0.6, color = color_map)
plt.gca().invert_yaxis()
ax.grid(axis='x', alpha=0.4)
plt.xlabel('Percent')
plt.ylabel('Phylum')
for index,data in enumerate(phyl_count['Phyl_Perc']):
plt.text(x=data+0.1, y=index+0.20,s=f'{data}%')
plt.show()
And I get this graph, how can I change Proteobacteria, Bacteriodata, etc to italic?
You can obtain a list of the labels by writing
labels = ax.get_yticklabels()
This gives you a list of the labels, where each label is an instance of Matplotlibs Text. This has a set_style-method, where one of the options is to set the text 'italic' so you can do
for lbl in labels:
lbl.set_style('italic')
I want to plot some impedance values and task and code are both simple. xhertz_df is a pandas dataframe and after conversion to a numpy array xhertz[0]is the real part, xhertz[1]the imaginary part and xhertz[3]represents the time between measurements.
def xhertz_plot(xhertz_df):
ax = plt.gca()
xhertz = xhertz_df.T.to_numpy()
ax.plot(xhertz[3], xhertz[0], 'green')
ax.plot(xhertz[3], xhertz[1], 'blue')
ax.scatter(xhertz[3], xhertz[0], cmap ='green')
ax.scatter(xhertz[3], xhertz[1], cmap ='blue')
ax.set_xlabel('Time Passed (in Minutes)')
plt.show()
I'm confused as to what can go wrong with this code as it seems so simple. Yet I get this result:
The upper line and points is a mix of blue and green even though it should be just green. The lower line that should be only blue has orange (?!) points. What is going on here?
Edit:
I found the problem: I used cmap instead of just c for the scatter plot. But to someone with expertise in both concepts: Why did I get the result shown above? E.g. where did the orange come from?
As stated in the docs for Axes.scatter:
A Colormap instance or registered colormap name. cmap is only used if c is an array of floats.
Since you did not provide a list of floats for the arg c, matplotlib ignored your cmap and instead used the first and second default colors (blue, then orange).
If you just want a single color, note the docs for the c argument:
If you wish to specify a single color for all points prefer the color keyword argument.
Alternatively, you can just use Axes.plot with o for the marker style, instead of scatter, e.g. ax.plot(x, y, 'o', color='green') or equivalently ax.plot(x, y, 'og'). This is more typical for simple plots; you can use - or o to explicitly set a line plot or marker plot.
Note that cmap is generally intended to be used if you want a different color for each point, like if you wanted to color the points to represent another dimension of data. In that case c would represent that third dimension of data, norm would scale the data, and cmap would be what colors are mapped to that data. See the scatter demo 2 from matplotlib for an example of how that argument is usually used.
I am drawing a few scatter plots in seaborn and they all come out with blue points:
I would like to change the color of the points. I found some rather complicated solutions where you can specify the color manually, but this is not what I want.
I don't care which color it is, it should just be different from blue and be one of the colors of the current palette to keep the visuals pleasing.
Is there something like start_with_palette_color=1 (default 0) in:
sns.scatterplot(data=tips, x="total_bill", y="tip", start_with_palette_color=1)
?
The current palette can be viewed with color_palette() when called without parameters. It returns a list of RGB tuples that represent the palette's colors.
scatterplot() accepts the named parameter color= to specify any color.
import seaborn as sns
tips = sns.load_dataset("tips")
# first scatter plot with default color
sns.scatterplot(data=tips, x="total_bill", y="tip")
# second scatter plot with the next color (array index 1 instead of implicit 0)
sns.scatterplot(data=tips, x="total_bill", y="tip",color=sns.color_palette()[1])
Anywhere matplotlib accepts a color, you can use "C{i}" to get the ith color in the current matplotlib cycle, which is probably the easiest way to accomplish this.
For example, "C0". Or "C3".
I'd like to superimpose one plot over another (they are polygons, really in some lat/lon space, using geopandas, but the plot is simply derived from matplotlib)
I have:
figZ, axZ = plt.subplots(1, figsize=(11,8.5))
Sfig = X.plot(ax=axZ, color='white', edgecolor='black', lw=0.7)
Y.plot(ax=axZ, color='white', edgecolor='black', lw=0.7, alpha=0.3)
How do I set Sfig's color to "no-fill" instead of white? The way it is now it "blurs" my Sfig image (X.plot) by the alpha of the Y.plot one. How do I set "color" to actually transparent?
I don't expect upvotes, but this is what I found as solution. I'll vote up better ones if they exist:
Sfig = X.plot(ax=axZ, facecolor="none",
edgecolor='black', lw=0.7)
I know this post doesn't mention seaborn, but I suspect a lot of people end up here asking this question for seaborn also (as I did).
The top answer almost works for seaborn boxplots, you just need to pass it as boxprops.
sns.boxplot(data=data, x=x, y=y, hue=hue, boxprops=dict(facecolor="none"))
NOTE: I emphasise that this solution only works for boxplots. There is an open, more general, feature request for this functionality in seaborn.
To disable facecolor just set with the value (0, 0, 0, 0), i.e.,
Sfig = set_facecolor((0,0,0,0))