For some reason, whenever I run the code below I get a Value Error: Could not convert string to float: 'A'
I change a comma to a decimal point below so the lengths line up between axes.
import numpy as np
import matplotlib.pyplot as plt
plt.rcdefaults()
%matplotlib inline
fig, ax = plt.subplots(1, 1, figsize=(12,9))
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
x_axis = 8.6667, 9.5, -8.4, 0, -4, 6
y_axis = 'A','B','C','D','E','F'
ind = np.arange(len(y_axis))
plt.xticks(fontsize=12)
plt.yticks(ind, y_axis, fontsize=14)
plt.tick_params(
axis='x',
which='both',
top='off')
plt.tick_params(
axis='y',
which='both',
right='off',
left='off')
plt.title('Super Awesome Title', fontsize=18, ha='center')
for a, b in zip(y_axis, ind):
plt.text(a, b, str(a), fontsize=16, color='black')
plt.barh(ind, x_axis)
Related
I wrote a code that read an excel sheet and plots a scatter figure with the following code:
fig, ax = plt.subplots(figsize=(13, 8))
scatter = ax.scatter(df.Date, df.TopAcc, c="blue", s=df.Param / 10000, alpha=0.2)
plot = ax.plot(dfmax.Date, dfmax.TopAcc, marker="o", c="red")
handles, labels = scatter.legend_elements(num=5, prop="sizes", alpha=0.2, color="blue")
legend = ax.legend(handles, labels, loc="lower right", title="# Parameters", )
plt.grid()
plt.show()
And I got the following figure
I have the following issues: How to prevent the legend balls from overlapping?
You can set columnspacing in the legend object:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig, ax = plt.subplots(figsize=(13, 8))
df = pd.DataFrame(np.random.rand(20, 2), columns=['x', 'y'])
df['s'] = 5000 * np.random.rand(20)
scatter = ax.scatter(df.x, df.y, c="blue", s=df.s, alpha=0.2)
handles, labels = scatter.legend_elements(num=5, prop="sizes", alpha=0.2, color="blue")
legend = ax.legend(handles, labels, loc="lower right", title="# Parameters", ncol=6, columnspacing=3, bbox_to_anchor=(1, -0.12), frameon=False)
plt.grid()
plt.show()
I Darw a graph with mutliple axix, have several questios:
why the left y-axsis is not satrting from zero. (I mean the zero point
is not at the begining of the y-axix).
I only want major grid for the x-axis (a major grid line for each week) but the code add a mjor
grid for the y-axix also.
How can i add minor grid for y-axix (the red one (ax2))
i want to change the color for the x-axis labels (Dates) color to black
import matplotlib.pyplot as plt
Hits= pd.read_excel("stackoverflow_example.xlsx", sheet_name="data")
fig=plt.figure(figsize=(20,10))
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax.bar(Hits['Date'], Hits['Total'], width=0.35, color="b" )
ax.set_ylabel('Hits', color="b",size=16)
ax.yaxis.set_label_position('right')
ax.tick_params(axis='y', colors="b")
ax.tick_params(axis='x', colors="b", rotation=45)
ax.yaxis.tick_right()
ax2.plot(Hits['weeks'], Hits['Cases'], linewidth= 3.5, color="Red")
ax2.set_ylabel("Cases", color="Red",size=16)
ax2.tick_params(axis='y', colors="Red", size=16)
ax2.xaxis.set_ticks_position('top')
major_ticks = np.arange(0, 10, 1)
ax.set_xticks(major_ticks)
ax.grid(which='major', alpha=0.5)
plt.show()
My data
[
Graph:
If you want to start from zero, you can do that with 'ax2.set_ylim()'. After that, you can specify the axes for the grid. If the color is black, you can set color='k'.
import matplotlib.pyplot as plt
fig=plt.figure(figsize=(20,10))
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax.bar(Hits['Date'], Hits['Total'], width=0.35, color="b" )
ax.set_ylabel('Hits', color="b",size=16)
ax.yaxis.set_label_position('right')
ax.tick_params(axis='y', colors="b")
ax.tick_params(axis='x', colors="k", rotation=45)
ax.yaxis.tick_right()
ax2.plot(Hits['weeks'], Hits['Cases'], linewidth= 3.5, color="Red")
ax2.set_ylabel("Cases", color="Red",size=16)
ax2.tick_params(axis='y', colors="Red", size=16)
ax2.xaxis.set_ticks_position('top')
ax2.set_ylim(0,62) # update
major_ticks = np.arange(0, 10, 1)
ax.set_xticks(major_ticks)
ax.grid(which='major', axis='x', alpha=0.5) #update
ax2.grid(which='major', axis='y', alpha=0.5) # update
plt.show()
How to add axis label (x and y) and rotate y axis numbers with Matplotlib like on the image below ?
I tried plt.yticks(rotation=45) to rotate the y axis numbers but it's not taken into account.
Besides, I'm also trying to have one 0 instead of two in my example code and a square grid instead of rectangles.
from mpl_toolkits.axisartist.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
for direction in ["xzero", "yzero"]:
# adds arrows at the ends of each axis
ax.axis[direction].set_axisline_style('->')
# adds X and Y-axis from the origin
ax.axis[direction].set_visible(True)
ax.axis['yzero'].set_ticklabel_direction("-")
for direction in ["left", "right", "bottom", "top"]:
# hides borders
ax.axis[direction].set_visible(False)
x = np.linspace(-5, 5, 100)
ax.plot(x, -x**2+16, color="#ab74a6", linewidth=3)
plt.title(r'$y = -x^2+16$')
plt.yticks(rotation=45)
plt.axis([-5, 5, -10, 20])
plt.grid(True)
plt.show()
Here's a working code example using spines rather than SubplotZero:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
x = np.linspace(-5, 5, 100)
ax.plot(x, -x**2+16, color="#ab74a6", linewidth=3)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# hide one of the zero labels and adjust the other
ax.yaxis.get_major_ticks()[3].label1.set_visible(False)
ax.xaxis.get_major_ticks()[3].label1.set_horizontalalignment("right")
ax.plot(1, 0, ">k", transform=ax.get_yaxis_transform(), clip_on=False)
ax.plot(0, 1, "^k", transform=ax.get_xaxis_transform(), clip_on=False)
ax.axis('equal')
ax.set_xlabel('x', position=(1,0), ha='right')
ax.set_ylabel('y', position=(0,1), ha='right', rotation=0)
plt.title(r'$y = -x^2+16$', y=1.08)
plt.grid(True)
plt.show()
My goal is to create plot with four subplots, where the bottom two are really just empty boxes where I will display some text. Unfortunately, all of my efforts to remove the y and x axis tick marks and labels have failed. I'm still new to matplotlib so I'm sure there's something simple that I'm missing. Here's what I'm trying and what I get:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2, sharex=False, sharey=True, figsize=(6,6))
fig.add_subplot(111, frameon=False)
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.title('Neuron Length')
plt.xlabel('Strain')
plt.ylabel('Neuron Length (um)')
aIP = fig.add_subplot(223, frameon=False)
aIP.annotate('Big Axes \nGridSpec[1:, -1]', (0.1, 0.5),
xycoords='axes fraction', va='center')
# First approach
aIP.axes.xaxis.set_ticks([])
aIP.axes.yaxis.set_ticks([])
# Second approach
ax = plt.gca()
ax.axes.yaxis.set_visible(False)
plt.show()
This is achieved by using plt.subplots() to draw four of them and remove the bottom left frame.
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(-np.pi, np.pi, 1000)
x1 = np.sin(2*t)
x2 = np.cos(2*t)
x3 = x1 + x2
fig,axes = plt.subplots(nrows=2,ncols=2,figsize=(6,6), sharex=True, sharey=True)
axes[0,0].plot(t, x1, linewidth=2)
axes[0,1].plot(t, x2, linewidth=2)
axes[1,1].plot(t, x3, linewidth=2)
axes[1,0].axis('off') # off
axes[1,0].annotate('Big Axes \nGridSpec[1:, -1]', (0.1, 0.5), xycoords='axes fraction', va='center')
fig.suptitle('Neuron Length')
for ax in axes.flat:
ax.set(xlabel='Strain', ylabel='Neuron Length (um)')
plt.show()
I have constructed a horizontal bar chart as show with the code below.
Everything looks great except what are supposed to be annotated bars.
I can't figure out how to get the labels on the end of the bars and not in a table in the middle of the chart. Specifically, I'm looking at these lines of code:
for i, text in enumerate(ind):
ax.annotate(str(x_axis), (ind[i], x_axis[i]),fontsize=14, color='black', va='center', ha='center')
Here's the whole thing:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
df0=pd.read_csv('sample1.csv')
fig, ax = plt.subplots(1, 1, figsize=(12,9))
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
x_axis = 8.6667, 9.5, -8.4, 0, -4, 6
y_axis = Hospital
y_axis = 'A','B','C','D','E','F'
ind = np.arange(len(y_axis))
plt.xticks(fontsize=12)
plt.yticks(ind, y_axis, fontsize=14)
plt.tick_params(
axis='x',
which='both',
top='off')
plt.tick_params(
axis='y',
which='both',
right='off',
left='off')
plt.title('Super Awesome Title', fontsize=18, ha='center')
#Label Bars: First is the older, simpler way but it has issues...
#for a, b in zip(ind, y_axis):
# plt.text(a, b, str(b), fontsize=16, color='black')
#Better, but more complex method:
for i, text in enumerate(ind):
ax.annotate(str(x_axis), (ind[i], x_axis[i]),fontsize=14, color='black', va='center', ha='center')
#Add padding around x_axis
plt.xlim([min(x_axis)-.5, max(x_axis)+.5])
#Add padding around y_axis
plt.ylim([min(ind)-.5, max(ind)+.5])
plt.barh(ind, x_axis, align='center', height=0.5, edgecolor='none', color='#AAA38E')
I just figured it out:
I had to switch ind and x_axis around and iterate over the x_axis:
ax.annotate(str(x_axis), (ind[i], x_axis[i])
should be:
ax.annotate(str(x_axis[i]), (x_axis[i], ind[i])