Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Supposing I have a Pandas DataFrame variable called df which has columns col1, col2, col3, col4.
Using sns.catplot() everything works fine:
fig = sns.catplot(x='col1', y='col2', kind='bar', data=df, col='col3', hue='col4')
However, as soon as I write:
fig.axes[0].get_xlabel()
I get the following error:
AttributeError: 'numpy.ndarray' object has no attribute 'get_xlabel'
I know I can use sns.barplot() with ax parameter but my goal is to keep using sns.catplot() and get an Axes object from fig.axes[0].
If you check the help page, it writes:
Figure-level interface for drawing categorical plots onto a FacetGrid
So to get the xlabel like you did:
import seaborn as sns
df = sns.load_dataset("tips")
g = sns.catplot(x='day', y='tip', kind='bar', data=df, col='smoker', hue='sex')
In this example, you have a facet plot that is 1 by 2, so the axes for the plots are stored in an (1,2) array:
g.axes.shape
(1, 2)
And to access for example the one of the left (Smoker ="Yes"), you do:
g.axes[0,0].get_xlabel()
'day'
To change the label:
g.axes[0,0].set_xlabel('day 1')
g.fig
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
In the data I'm working with, it's more valuable to see what values are greater than or less than one, and I want to show this with bars that go in opposite directions. This happens naturally for values greater than or equal to zero. How do I change this?
So far I have visual solution, but the axis values then aren't correct.
plt.barh(weights_df['Variable'],weights_df['Odds Ratio']-1, color="Purple", align='edge', label='Odds Ratio')
plt.xlabel('Odds Ratio')
plt.ylabel('Variable')
plt.title("Odds Ratios")
plt.show()
Sample data:
weights = {
'Age': 0.42,
'Location': 1.5,
'Smoke': 2.9,
'Lesion': 0.22,
}
with the given data and that it is easy to plot works well naturally well with zero, one way to show the plot is to do what you have done above and edit the labels. Use get_xticklables() and set_xticklables() after adding 1 to the axis. See if this works. Code below..
weights_df = pd.read_excel('myinput.xlsx', 'Sheet56')
fig, ax1 = plt.subplots()
ax1.barh(weights_df['Variable'],weights_df['Odds Ratio'] - 1, color="Purple", align='edge', label='Odds Ratio')
labels = ax1.get_xticks().tolist() ## Get the x-axis labels
labels = [x + 1 for x in labels] ## Add 1 to each label
ax1.set_xticks(ax1.get_xticks().tolist())
ax1.set_xticklabels(labels) ## Set the x-axis labels to new values
plt.xlabel('Odds Ratio')
plt.ylabel('Variable')
plt.title("Odds Ratios")
plt.show()
Plot
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need a replacement for the tf.browser.toPixels() tensorflowJS function. Trying to port some code to python and I'm wondering if there is a quick way around this.
In the browser this gets really simple and we just callback new frames and draw into a canvas. But in python development, say in matplotlib or tkinter, I guess I'm gonna need some tricks.
Is there a (not super big) solution for this?
Thanks
Let say you are having a 2D tensor img which run it in your browser like tf.browser.toPixels(img). You can draw similar images using OpenCV and matplotlib like:
Using Pytorch
import matplotlib.pyplot as plt
# If your data is in GPU:
img_np = img.cpu().numpy()
# Using OpenCV
cv2.imwrite(img_np.astype(np.uint8), "image.png")
# Using matplotlib
plt.imshow(img_np)
Tensorflow
```python
import matplotlib.pyplot as plt
img_np = img.numpy()
# Using OpenCV
cv2.imwrite(img_np.astype(np.uint8), "image.png")
# Using matplotlib
plt.imshow(img_np)
Also, if you have a 3D tensor ( i.e. n x m x 3) you can still average the bands and make a 2D tensor out of it and plot them the same way.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am figuring out how to use the np.polyfit function and the documentation confuses me. In particular, I am trying to perform linear regression and print related statistics like the sum of squared errors (SSE). Can someone provide clear and concise explanations, possibly with a minimal working example?
np.polyfit returns a tuple containing the coefficients parametrizing the best-fitting polynomial of degree deg. To fit a line, use deg = 1. You can return the residual (sum of squared errors) by passing full = True as an argument to polyfit. Note that with this argument, polyfit will also return some other information about the fit, which we can just discard.
Altogether, then, we have might have something like
import matplotlib.pyplot as plt
import numpy as np
# Generate some toy data.
x = np.random.rand(25)
y = 2 * x + 0.5 + np.random.normal(scale=0.05, size=x.size)
# Fit the trend line.
(m, b), (SSE,), *_ = np.polyfit(x, y, deg=1, full=True)
# Plot the original data.
plt.scatter(x, y, color='k')
# Plot the trend line.
line_x = np.linspace(0, 1, 200)
plt.plot(line_x, m * line_x + b, color='r')
plt.title(f'slope = {round(m, 3)}, int = {round(b, 3)}, SSE = {round(SSE, 3)}')
plt.show()
The *_ notation in the call to polyfit just tells Python to discard however many additional values are returned by the function. The documentation can tell you about these extra values if you're interested. We have to parse the SSE as a tuple (SSE,) because polyfit returns it as a singleton array. This code produces something like this plot.
You might also like to know about np.polyval, which will take tuples of polynomial coefficients and evaluate the corresponding function at input points.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
X axis contains 80 different variables. The green dots represent performance. The red/blue lines denote the increase/decrease in performance respectively. I was thinking of a box plot/scatter plot, but what I need I think is a combination of the two. Any help is appreciated.
I would make a scatter plot where the dot represents performance and the red/blue lines are represented as yerr.
import numpy as np
import matplotlib.pyplot as plt
y = [20, 30, 40]
x = np.arange(0,len(y), 1)
xlabel = ['airplane', 'apple', 'banana']
change = [-10,0,+3]
y_err,err_color = [],[]
for i in change:
if i < 0 :
y_err.append([[abs(i)],[0]])
err_color.append(['blue'])
else:
y_err.append([[0],[i]])
err_color.append(['red'])
for i in range(len(x)):
print(y_err[i])
plt.errorbar(x[i], y[i], yerr = y_err[i], color = 'green',fmt='.',ecolor =
err_color[i])
plt.xticks(x, xlabel,rotation = 'vertical')
plt.show()
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm having trouble converting a tuple containing the coordinates of polygon vertices to a shapefile.
Tuples are a very unfamiliar format to me; if it were in a dataframe, I could do it easily with geopandas.
shape= ({'type': 'Polygon',
'coordinates': [[(-148.7285301097261, 60.42704276401832),
(-148.7285301097261, 60.42693172262919),
(-148.7285856304207, 60.42693172262919),
(-148.72830802694787, 60.42704276401832),
(-148.7285301097261, 60.42704276401832)]]},
1.0)
I can't convert to dataframe via pd.DataFrame(shape); can't subset the tuple to access coordinates via shape['coordinates'] or pd.DataFrame(list(shape)). I've reviewed this, and this, but am stuck on getting the coordinates out of the Tuple structure!
How can I create a shapefile (via Geopandas), given a tuple of the structure shown here?
You should be able to convert it to pandas DataFrame by reading the first element of the tuple:
pd.DataFrame(shape[0]).explode('coordinates')
Out[1]:
type coordinates
0 Polygon (-148.7285301097261, 60.42704276401832)
0 Polygon (-148.7285301097261, 60.42693172262919)
0 Polygon (-148.7285856304207, 60.42693172262919)
0 Polygon (-148.72830802694787, 60.42704276401832)
0 Polygon (-148.7285301097261, 60.42704276401832)
If you need to split into x and y you can just take the items from the series:
df = pd.DataFrame(shape[0]).explode('coordinates').reset_index(drop=True)
df = df.join(df['coordinates'].apply(pd.Series)).rename(columns={0:'x', 1:'y'}).drop('coordinates', axis=1)
Out[2]:
type x y
0 Polygon -148.728530 60.427043
1 Polygon -148.728530 60.426932
2 Polygon -148.728586 60.426932
3 Polygon -148.728308 60.427043
4 Polygon -148.728530 60.427043