Is it possible to get a list of colors used in a plot?
Consider this example:
line1 = ax1.plot(x1,y1)
line2 = ax1.plot(x2,y2)
I now how to set the color
plt.setp(line1,'color','red')
plt.setp(line2,'color','red')
but is there a way how to learn what color has been used? plt.getp(line1,'color') does not work and complains that
AttributeError: 'list' object has no attribute 'get_color'
OK, found an answer: The plot() call returns a list of lines. The correct way to query the color is
print line1[0].get_color()
Related
I'm trying to display the exact values on one axis of the color bar and a basic scale on the other. However, some of the exact values are so close together their names overlap on the color bar. Is there a way for me to make the overlapping names appear as a list or just to the side the other values name? I've already tried rotation of the labels, setting vmin/vmax in the color bar method, and setting the ylim's of the second axis. I'm at a lose at what to try next. It feels like this is something matplotlib would allow but I can't find what method or kwargs that allow this manipulation. Many of the commented out tlines are the attempts I've made with help from many posts on StackOverflow. Thank you!!
Previous code deleted for clarity
UPDATE: Paul H here is a workable example with the same issue I'm trying to fix
# Make random data with same issue
x, y = np.linspace(-3, 1.5, 20), np.linspace(0, 0.5, 20)
# two different ranges used to simulate the same issue in my data
fake_phase = np.append(np.random.random_sample(15), np.arange(0.0, .005, 0.001))
fake_labels = np.array(['V439Oph', 'ALVir', 'YZVir', 'XXVir', 'V716Oph', 'BFSer', 'BLHer',
'RXLib', 'CEHer', 'V465Oph', 'V1180Sgr', 'CSCas', 'DQAnd', 'IXCas',
'UYEri', 'TWCap', 'AUPeg', 'MZCyg', 'SWTau', 'TXDel'], dtype=object)
# Plot data
fig, ax = plt.subplots(1,1,figsize=(15,10))
plt.tight_layout()
plt.plot(x, y, marker='.', ms=17, mew=2, linestyle='none')
# Make the same colorbar
norm = cm.colors.Normalize(vmin=0.0, vmax=1.0, clip=False)
cbar = fig.colorbar(cm.ScalarMappable(norm=norm, cmap='rainbow'), ax=ax, extend='both',
orientation='vertical', pad=0.005, use_gridspec=True)
cbar.set_ticks(fake_phase)
cbar.set_ticklabels(fake_labels)
cbar.ax.tick_params(which='major', labelsize='large', width=1.5, length=6)
cbar.set_label(label='Phase', size='xx-large', labelpad=40)
cbar.ax.set_aspect('auto')
ax2 = cbar.ax.twinx()
pos = cbar.ax.get_position()
pos.x0 += 0.1
ax2.set_position(pos)
plt.show();
The output of this code: Output of workable example
My issue is that the secondary axis on the colorbar (left axis) has values that are so close together their labels overlap. I'm hoping to find a way to space the labels so they are readable. I thought I found a way to accomplish this using axis.set_ticklabels() (set_ticklabels() documentation. In the **kargs section of the doc it references using text properties. In the text properties documentation text properties doc the property 'y' says you can set the y-position of the text. However, when I add this keyword to set_ticklabels() I get an error that the keyword is not recognized.. I've tried adding the property 'y' as a keyword and attribute but I get a keyword error or does not have that attribute error...
I'm calling the property wrong but I've never gotten this detailed in editing these parameters. I honestly don't know if this is the best way to solve this, but it's the closest I've gotten so far. I was hoping to use it to offset the labels so they were stacked vertically on top of each other in the same order but far enough apart that the label is readable.
Thanks for any input!
I'm trying to convert a list of hex codes to an sns.color_palette and then using it as a color palette for a bar plot -
plt.figure(figsize=(10,5))
colors = sns.color_palette(['#f15a22', '#9db1bb', '#f26b38', '#f47b4e', '#f58c64', '#f79c7a', '#bb1d8d', '#f8ad91',
'#00aeef', '#fbcebd', '#fcded3', '#feefe9', '#c23498', '#fbca8e'])
sns.barplot(organizations.index, organizations.values, color=colors)
But this keeps returning me an error -
ValueError: Invalid RGBA argument.
The hex codes work fine when I use them as sns.palplot(colors), and I've checked that the number of color codes are also equal to the number of bars (data rows) to be produced.
Can someone please tell me what I'm doing wrong?
My bad! It should be
palette = colors
I need to plot line plot that has different colors. I create special df column 'color' that contains for each point appropriate color.
I already found the solution here:
python/matplotlib - multicolor line
And take the approach from the above question. First, it was working when I use index but now I need to plot it vs other column and I can not appropriately handle the colors. It is all the time colores only with one color.
I use this code for setting colors, but it color line with one color that is the last in the column 'color'. And also create a legend that I don't understand how to delete from the plot.
for color2, start, end in gen_repeating(df2['color']):
print(start, end)
if start > 0: # make sure lines connect
start -= 1
idx = df2.index[start:end+1]
x2 = idx
y2 = df2.loc[idx, 'age_gps_data'].tolist()
df2.plot(x='river_km', y='age_gps_data', color=color2, ax=ax[1])
ax[1].xaxis.set_major_locator(plt.MaxNLocator(5))
plt.setp(ax[1].get_xticklabels())
I would appreciate any help.
How can I set these colors to achieve different color in one line? And don't have legend on the plot.
I am trying to make a function that gets an inputted string and returns it with a random colour. (The random colour is defined earlier)
print(Fore.randomColour + inputVariable)
Whenever I try something along those lines, I end up with the error:
AttributeError: 'AnsiFore' object has no attribute 'randomColour'
I have tried using getattr, but I still couldn't get it to work. Any help will be much appreciated. Thanks.
You can make a list with your defined colors and then pick it randomly.
import random
bcolors = ['\033[95m','\033[94m','\033[92m','\033[93m','\033[91m','\033[1m']
print (random.choice(bcolors) + "random color" + '\033[0m')
where '\033[0m' means reset
How can I split the ylabel of a matplotlib figure into rows? I want to keep the ylabel on the y-axis rotated. As an example, here's my subplot so far, for which the relevant part of the code is below:
plt.ylabel('Spacing of Zeroes of $J_{\\nu}(x)$', rotation=0)
When I try doing this:
plt.ylabel('Spacing of Zeroes of $J_{\\nu}(x)$', rotation=0, ncol=2)
I receive this error:
AttributeError: Unknown property ncol
My suggestion would be to introduce linebreaks in the string.
plt.ylabel('Spacing of\nZeroes of\n$J_{\\nu}(x)$', rotation=0, ha="right")
You can use this.
https://matplotlib.org/2.0.2/examples/pylab_examples/multiline.html
plt.xlabel('this is a xlabel\n(with newlines!)')
plt.ylabel('this is vertical\ntest', multialignment='center')