when I use bar_chart_race, it shows this waring: how to solve it since inside there is no parameter on the set_yticklabels?
C:\ProgramData\Anaconda3\lib\site-packages\bar_chart_race_make_chart.py:286: UserWarning: FixedFormatter should only be used together with FixedLocator
ax.set_yticklabels(self.df_values.columns)
Related
I'm using pycharm to run some code using Seaborn. I'm very new to python and am just trying to learn the ropes so I'm following a tutorial online. I've imported the necessary libraries and have run the below code
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# import the data saved as a csv
df = pd.read_csv('summer-products-with-rating-and-performance_2020-08.csv')
df["has_urgency_banner"] = df["has_urgency_banner"].fillna(0)
df["discount"] = (df["retail_price"] -
df["price"])/df["retail_price"]
df["rating_five_percent"] = df["rating_five_count"]/df["rating_count"]
df["rating_four_percent"] = df["rating_four_count"]/df["rating_count"]
df["rating_three_percent"] = df["rating_three_count"]/df["rating_count"]
df["rating_two_percent"] = df["rating_two_count"]/df["rating_count"]
df["rating_one_percent"] = df["rating_one_count"]/df["rating_count"]
ratings = [
"rating_five_percent",
"rating_four_percent",
"rating_three_percent",
"rating_two_percent",
"rating_one_percent"
]
for rating in ratings:
df[rating] = df[rating].apply(lambda x: x if x>= 0 and x<= 1 else 0)
# Distribution plot on price
sns.histplot(df['price'])
My output is as follows:
Process finished with exit code 0
so I know there are no errors in the code but I don't see any graphs anywhere as I'm supposed to.
Ive found a way around this by using this at the end
plt.show()
which opens a new tab and uses matplotlib to show me a similar graph.
However in the code I'm using to follow along, matplotlib is not imported or used (I understand that seaborn has built in Matplotlib functionality) as in the plt.show statement is not used but the a visual graph is still achieved.
I've also used print which gives me the following
AxesSubplot(0.125,0.11;0.775x0.77)
Last point to mention is that the code im following along with uses the following
import seaborn as sns
# Distribution plot on price
sns.distplot(df['price'])
but distplot has now depreciated and I've now used histplot because I think that's the best alternative vs using displot, If that's incorrect please let me know.
I feel there is a simple solution as to why I'm not seeing a graph but I'm not sure if it's to do with pycharm or due to something within the code.
matplotlib is a dependency of seaborn. As such, importing matplotlib with import matplotlib.pyplot as plt and calling plt.show() does not add any overhead to your code.
While it is annoying that there is no sns.plt.show() at this time (see this similar question for discussion), I think this is the simplest solution to force plots to show when using PyCharm Community.
Importing matplotlib in this way will not affect how your exercises run as long as you use a namespace like plt.
Be aware the 'data' must be pandas DataFrame object, not: <class 'pandas.core.series.Series'>
I using this, work finely:
# Distribution plot on price
sns.histplot(df[['price']])
plt.show()
I'm trying to use sympy to plot an implicitly defined function in python, and have found the built-in plotting functionality to be sorely lacking. The source code recommends using _backend to directly modify the matplotlib axis and figure objects. Here's an abbreviated version of my code:
import matplotlib
from sympy import symbols, exp, plot_implicit, Eq
V,I = symbols('V I')
#define implicit equation to plot
eq1 = Eq(exp(I+V)-I,0)
#plot equation
p1 = plot_implicit(eq1, V,I)
#use _backend.ax to set xlabel and title of plot
axis = p1._backend.ax
axis.set_xlabel('Voltage (V)')
axis.set_title('ooga')
p1._backend.fig.savefig('test.png')
p1.show()
But when I run it, I get the following output:
plot generated without specified axis label and title
AttributeError: 'list' object has no attribute 'set_xlabel'
Why isn't this working? I don't understand why my axis object is being saved as a list. (Also, I find it rather odd that I get any plot output at all, as this would seem to imply the plot is being generated before I call p1.show())
Edit:
I've resolved the issue by following JohanC's recommendation to use move_sympyplot_to_axes from this post. Unfortunately I was unable to get ._backend working as intended, but this solution works well enough for my purposes.
There are many questions related to the question title above and all basically tell you to do:
import warnings
warnings.filterwarnings('ignore')
and to make sure this is placed before the first import.
However, even after doing this I get many warnings from seaborn and sklearn. I get UserWarning, DataConversionWarning and RuntimeWarning which, according to documentation, all inherit from Warning and should be covered by the above code.
Is there another way to hide those warnings?
(I cannot really solve most of them anyway)
EDIT
Example 1:
C:\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py:645: DataConversionWarning: Data with input dtype int32, int64 were all converted to float64 by StandardScaler.
return self.partial_fit(X, y)
Example 2
C:\Anaconda3\lib\site-packages\seaborn\distributions.py:340: UserWarning: Attempted to set non-positive bottom ylim on a log-scaled axis.
Invalid limit will be ignored.
ax.set_ylim(0, auto=None)
Example2
It's a bit hard to track down; seaborn imports statsmodels. And in statsmodels/tools/sm_exceptions.py you find this line
warnings.simplefilter('always', category=UserWarning)
in which reverses any previous setting for user warnings.
A solution for now would be to remove that line or to set the warning state after the import of seaborn (and hence statsmodels). In a future version of statsmodels this will be fixed by PR 4712, so using the development version of statsmodels would also be an option.
Example1
I did not find a way to reproduce the first example from sklearn; so that may or may not have a different reason.
I'm studying matplotlib and don't know how to just save the graph and not print it on the screen.
So I've done some research on the Internet, many answers said the solution is matplotlib.use('Agg'). And it must be before importing matplotlib.pyplot or pylab.
Then when I added it in the first line of my script, it doesn't work at all.
import matplotlib
matplotlib.use('Agg')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
E:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py:1401: UserWarning: This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
warnings.warn(_use_error_msg)
I use Anaconda Spyder, so I restarted kernel and ran my script again, I got same wrong information.
Then I restarted kernel again and directly typed the following code in the console:
In[1]: import matplotlib as mpl
In[2]: mpl.use('Agg')
E:\Program Files\Anaconda3\lib\site-packages\matplotlib\__init__.py:1401: UserWarning: This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
warnings.warn(_use_error_msg)
Also, if I delete 'plt.show()' at the end of script or add 'plt.ioff()', the graph will always print on the screen.
Thanks for everyone's answer. Now I have two solutions:
just use plt.close() , this will not change the backend and the figure doesn't show up.
use plt.switch_backend('Agg'), this will switch the backend to 'agg' and no figure printed on the screen.
You can try to switch the backend. Apparently Spyder loads matplotlib before you do, and use has no effect. This may be helpful:
How to switch backends in matplotlib / Python
The answer to your original question is simple.
If you don't want to show the graph on screen, just don't use plt.show()
So what you've gotta do is simply:
import matplotlib.pylab as plt
plt.plot(x,y) #whatever the x, y data be
#plt.show() """Important: either comment this line or delete it"""
plt.savefig('path/where/you/want/to/save/filename.ext')
#'filename' is either a new file or an already existing one which will get overwritten at the time of execution. 'ext' can be any valid image format including jpg, png, pdf, etc.
plt.plot(x,y)
plt.savefig('path/figure_filename.jpg',dpi=300)
I am using PyCharm 2016.1 and Python 2.7 on Windows 10 and imported the matplotlib module.
As the matplotlib module ist very extensive and I am relatively new to Python, I hoped the Auto Complete function in PyCharm could help me to get an overview of the existent properties/ functions of an object. It would be more convenient as digging through the api documentation every time, not knowing what to look for an where to find it.
For example:
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
When I type ax. there ist no auto completion for the properties, functions etc. of the axis, I only get the suggestions list.
I already tried this and imported the axis module directly with:
import matplotlib.axis as axis
or
from matplotlib.axis import Axis as axis
Smart Auto Completion and 'Collect run-time types information' is already enabled.
Is there a way to enable the auto completion like described or is there another IDE that supports that?
I believe your problem is highlighted here:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/205816499-Improving-collecting-run-time-type-information-for-code-insight?sort_by=votes
Tldr return types can vary, so it cant be figured out at compile time.
Most accepted way is to use a type hint, since it can only figure out what type it as run time :
import matplotlib.axes._axes as axes
fig = plt.figure(figsize=(5,10))
ax1 = fig.add_subplot(3,1,1) # type:axes.Axes
ax1.set_xlabel('Test') <- now autocompletes
You can also try an assert isinstance:
import matplotlib.axes._axes as axes
fig = plt.figure(figsize=(5,10))
ax1 = fig.add_subplot(3,1,1)
assert isinstance(ax1, axes.Axes)
ax1.set_xlabel('Test')
It wont find the autocomplete if you do it after the method you are looking for:
ax1.set_xlabel('Test')
assert isinstance(ax1, axes.Axes)
With this, you shouldnt let isinstance dictate the control flow of your code, if you are trying to run a method that doesnt exist on an object, it should crash, however, if your different object has a method of the same name (!) then you have inadvertently reached that goal without annotations being there. So I like it better, since you want it to crash early and in the correct place. YMMV
From the doc:
Assertions should not be used to test for failure cases that can
occur because of bad user input or operating system/environment
failures, such as a file not being found. Instead, you should raise an
exception, or print an error message, or whatever is appropriate. One
important reason why assertions should only be used for self-tests of
the program is that assertions can be disabled at compile time.
If Python is started with the -O option, then assertions will be
stripped out and not evaluated. So if code uses assertions heavily,
but is performance-critical, then there is a system for turning them
off in release builds. (But don't do this unless it's really
necessary.
https://wiki.python.org/moin/UsingAssertionsEffectively
Alternatively, if you dont want to add to your code in this fashion, and have Ipython/jupyter installed through anoconda, you can get the code completion from the console by right clicking the code to be ran and choosing "execute selection in console"
In addition to Paul's answer. If you are using fig, ax = plt.subplots() , you could use figure type hint. See below example:
from matplotlib import pyplot as plt
import matplotlib.axes._axes as axes
import matplotlib.figure as figure
fig, ax = plt.subplots() # type:figure.Figure, axes.Axes
ax.
fig.