category stringclasses 107
values | title stringlengths 15 179 | question_link stringlengths 59 147 | question_body stringlengths 53 33.8k | answer_html stringlengths 0 28.8k | __index_level_0__ int64 0 1.58k |
|---|---|---|---|---|---|
spaCy | Import spaCy error | https://stackoverflow.com/questions/46887236/import-spacy-error | <p>When I try to import <a href="https://spacy.io/" rel="nofollow noreferrer">spaCy</a> (for the first time), I get the follwoing error:</p>
<pre><code>>>>import spacy
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import spacy
File "/Library/Frameworks/Python.f... | <p>It could be a version conflict with either <code>thinc</code> or <code>spacy</code>. It has been fixed in thinc v6.9.0! </p>
<p>I would suggest you uninstall by using <code>sudo pip uninstall thinc</code> or <code>sudo pip3 uninstall thinc</code> and reinstall the thinc version 6.9.0 provided here: <a href="https:/... | 934 |
spaCy | SpaCy can't find table(s) lexeme_norm for language 'en' in spacy-lookups-data | https://stackoverflow.com/questions/66367447/spacy-cant-find-tables-lexeme-norm-for-language-en-in-spacy-lookups-data | <p>I am trying to train a text categorization pipe in SpaCy:</p>
<pre class="lang-py prettyprint-override"><code>import spacy
nlp = spacy.load("en_core_web_sm")
nlp.add_pipe("textcat", last=True)
other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'textcat']
with nlp.disable_pipes(*other_pipe... | <p>It isn't allowed to call <code>nlp.begin_training()</code> on pretrained models. If you want to train a new model, just use:
<code>nlp = spacy.blank('en')</code>
instead of <code>nlp = spacy.load("en_core_web_sm")</code></p>
<p>However, if you want to continue training on an existing model call <code>optim... | 935 |
spaCy | Failed building wheel for spacy | https://stackoverflow.com/questions/43370851/failed-building-wheel-for-spacy | <p>I'm trying to install spacy by running <code>pip install spacy</code> for python version <strong>3.6.1</strong> but continuously i'm getting errors like below,how to get rid of this issue? previously i was having cl.exe not found error, after that i added visual studio path in environment variables where cl.exe exis... | <p>A couple thoughts:</p>
<ul>
<li><s>Grab the various wheel files you need from <a href="http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#spacy" rel="nofollow noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#spacy</a> and install with <code>pip install x.whl y.whl etc.</code></s></li>
<li>Upgrade your version of cpp... | 936 |
spaCy | Similarity in Spacy | https://stackoverflow.com/questions/53453559/similarity-in-spacy | <p>I am trying to understand how similarity in Spacy works. I tried using Melania Trump's <a href="http://time.com/4412008/republican-convention-melania-trump-2/" rel="noreferrer">speech</a> and Michelle Obama's <a href="https://www.npr.org/templates/story/story.php?storyId=93963863" rel="noreferrer">speech</a> to see ... | <p>By default spaCy calculates cosine similarity. <a href="https://spacy.io/usage/vectors-similarity" rel="noreferrer">Similarity</a> is determined by comparing word vectors or word embeddings, multi-dimensional meaning representations of a word.</p>
<p>It <a href="https://github.com/explosion/spaCy/blob/master/spacy/... | 937 |
spaCy | Latest version of spacy-lefff incompatible with latest version of spacy | https://stackoverflow.com/questions/55309497/latest-version-of-spacy-lefff-incompatible-with-latest-version-of-spacy | <p>Installation of spacy-lefff v. 0.3.3 makes it impossible to run a Python program with module Spacy (v. 2.1.1)</p>
<p>The root problem seems to be the modules thinc and cymem. I tried to unstalled thinc and cymem but i don't know which version of thinc and cymem to reinstall afterwords.</p>
<p>There is no indicatio... | 938 | |
spaCy | Spacy-Transformers: Access GPT-2? | https://stackoverflow.com/questions/68946827/spacy-transformers-access-gpt-2 | <p>I'm using Spacy-Transformers to build some NLP models.</p>
<p>The <a href="https://spacy.io/universe/project/spacy-transformers#gatsby-noscript" rel="nofollow noreferrer">Spacy-Transformers docs</a> say:</p>
<blockquote>
<p><strong>spacy-transformers</strong></p>
<p><em>spaCy pipelines for pretrained BERT, XLNet and... | <p>The <code>en_core_web_trf</code> uses a specific Transformers model, but you can specify arbitrary ones using the <code>TransformerModel</code> wrapper class from <code>spacy-transformers</code>. See <a href="https://spacy.io/api/architectures#TransformerModel" rel="nofollow noreferrer">the docs</a> for that. An exa... | 939 |
spaCy | ModuleNotFoundError: No module named 'spacy' even though spacy and python are in the same path | https://stackoverflow.com/questions/69716018/modulenotfounderror-no-module-named-spacy-even-though-spacy-and-python-are-in | <p>I am following the spaCy installation guideline inside my AWS SageMaker notebook</p>
<pre><code>pip install -U pip setuptools wheel
pip install -U spacy
python -m spacy download en_core_web_sm
</code></pre>
<p>When I do <code>import spacy</code> I get error</p>
<pre><code>ModuleNotFoundError: No module named 'spacy'... | <p>If you are installing spacy from inside the jupyter notebook, use the <code>%pip</code> syntax. That will use the pip associated with the kernel in use.</p>
<pre><code>%pip install spacy
</code></pre>
<p>If installing from the command line, use</p>
<pre><code>python -m pip install spacy
</code></pre>
<p>(Replace <co... | 940 |
spaCy | Using Arabert model with SpaCy | https://stackoverflow.com/questions/74062240/using-arabert-model-with-spacy | <p>SpaCy doesn't support the Arabic language, but Can I use SpaCy with the pretrained Arabert model?</p>
<p>Is it possible to modify this code so it can accept bert-large-arabertv02 instead of en_core_web_lg?</p>
<pre><code>!python -m spacy download en_core_web_lg
import spacy
nlp = spacy.load("en_core_web_lg"... | <p>spaCy actually does support Arabic, though only at an alpha level, which basically just means tokenization support (see <a href="https://spacy.io/usage/models#languages" rel="noreferrer">here</a>). That's enough for loading external models or training your own, though, so in this case you should be able to load this... | 941 |
spaCy | Collocations with spaCy | https://stackoverflow.com/questions/39258476/collocations-with-spacy | <p>I've been using NLTK for finding collocations, or n-grams, and have recently discovered the spaCy module for NLP. I've only just begun familiarizing myself with it and have, thus far, seen little mention for supported collocation functions.</p>
<p>Can spaCy be used to find collocations directly?</p>
<p>I have read... | <p>Collocations detection also can be based on dependency parsing, but spaCy do not have support to do it. You can use spaCy as part of an approach, but not directly.</p>
<p>may you also consider gensim:
<a href="https://radimrehurek.com/gensim/models/phrases.html" rel="noreferrer">https://radimrehurek.com/gensim/mode... | 942 |
spaCy | spaCy and Docker: can't "dockerize" Flask app that uses spaCy modules | https://stackoverflow.com/questions/67394064/spacy-and-docker-cant-dockerize-flask-app-that-uses-spacy-modules | <p>I'm trying to install SpaCy on my docker image but it always fails. First it was on my requirements.txt file, but it failed right away. Later on I tried running a separate RUN instruction for pip to install it in isolation but it also failed.</p>
<p>Here's my Dockerfile content:</p>
<pre><code>FROM python:3.6-alpine... | <p>The <a href="https://github.com/explosion/spaCy/issues/6158" rel="nofollow noreferrer">spacy installation extremely slow in docker</a> Github issue explains the problem with the Alpine Python docker (I see you have <code>FROM python:3.6-alpine</code> in your dockerfile):</p>
<blockquote>
<p>If you're using an Alpine... | 943 |
spaCy | Spacy Verb highlight? | https://stackoverflow.com/questions/51739273/spacy-verb-highlight | <p>Just like spacy displacy renders entity highlights in html.</p>
<pre><code>import spacy
from spacy import displacy
nlp = spacy.load('en')
doc1 = nlp(u'This is a google sentence.')
doc2 = nlp(u'This is another sentence.')
html = displacy.render([doc1, doc2], style='ent', page=True)
</code></pre>
<p>How to highlight... | <p>You can use displacy ent interface to highlight custom entities by setting <code>manual=True</code> on either <code>render()</code> or <code>serve()</code>.
Here is a simple example:</p>
<pre><code>sentence = [{'text': 'The cat jumped quickly over the wall.',
'ents': [{'start': 8, 'end':14, 'label': 'VERB'}],
... | 944 |
spaCy | Failed to load spaCy model 'en_core_web_sm' | https://stackoverflow.com/questions/63683431/failed-to-load-spacy-model-en-core-web-sm | <p>Being complete python novice, I am trying to learn some spaCy basics. Problem is, I can not load any models.</p>
<p>I am using Microsoft Visual Studio Community(MVSC), Windows 7, Python 3.7.5., pip 19.2.3 spaCy has been installed via pip on Python 3.7 (64-bit) environment.</p>
<p>(1) when I run in MVSC:</p>
<pre cla... | <p>Have you checked the project's GitHub repo? There is a closed issue that seems to be close (minus the spaCy version you're using)</p>
<p><a href="https://github.com/explosion/spaCy/issues/4577" rel="noreferrer">https://github.com/explosion/spaCy/issues/4577</a></p>
<blockquote>
<p>When you run <code>python -m spacy ... | 945 |
spaCy | Remove Spacy downloaded model | https://stackoverflow.com/questions/50344228/remove-spacy-downloaded-model | <p>After downloading and linking a spacy model (en large) by:</p>
<pre><code>python -m spacy download en_core_web_lg
</code></pre>
<p>which is around 850 Mb of data.</p>
<p>How can it find and delete the data (downloaded model) on my mac to free some space?</p>
<pre><code>Spacy: 2.0.18
Python: 3.6.9
en_core_web... | <p>The <code>download</code> command will install the model via <code>pip</code>, place the package in your <code>site-packages</code>. So, the data should be inside the <code>spacy</code> directory inside your python's <code>site-packages</code>.
Try to check some where like <code>/usr/lib/python3.6/site-packages/en_c... | 946 |
spaCy | Spacy MemoryError | https://stackoverflow.com/questions/54014422/spacy-memoryerror | <p>I managed to install spacy but when trying to use nlp then I am getting a MemoryError for some weird reason.</p>
<p>The code I wrote is as follows:</p>
<pre><code>import spacy
import re
from nltk.corpus import gutenberg
def clean_text(astring):
#replace newlines with space
newstring=re.sub("\n"," ",astrin... | <p>I'm guessing you truly are running out of memory. I couldn't find an exact number, but I'm sure Carrol's Alice's Adventures in Wonderland has tens of thousands of sentences. This equates to tens of thousands of <code>Span</code> elements from Spacy. Without modification, <code>nlp()</code> determines everything from... | 947 |
spaCy | Can older spaCy models be ported to future spaCy versions? | https://stackoverflow.com/questions/79583668/can-older-spacy-models-be-ported-to-future-spacy-versions | <p>The latest spaCy versions have better performance and compatibility for GPU acceleration on Apple devices, but I have an existing project that depends on spaCy 3.1.4 and some of the specific behavior of the 3.1.0 models (web lg, web trf).</p>
<p>Would it be possible to port the old models from source to work with ne... | 948 | |
spaCy | spaCy Alternatives in Java | https://stackoverflow.com/questions/41196081/spacy-alternatives-in-java | <p>I currently use spaCy to traverse the dependency tree, and generate entities. </p>
<pre><code>nlp = get_spacy_model(detect_lang(unicode_text))
doc = nlp(unicode_text)
entities = set()
for sentence in doc.sents:
# traverse tree picking up entities
for token in sentence.subtree:
## pick entitites using some... | <p>You're looking for the <a href="http://nlp.stanford.edu/software/nndep.shtml" rel="nofollow noreferrer">Stanford Dependency Parser</a>. Like most of the Stanford tools, this is also bundled with <a href="http://stanfordnlp.github.io/CoreNLP/" rel="nofollow noreferrer">Stanford CoreNLP</a> under the <code>depparse</c... | 949 |
spaCy | Python: Spacy and memory consumption | https://stackoverflow.com/questions/55841087/python-spacy-and-memory-consumption | <h2>1 - THE PROBLEM</h2>
<p>I'm using "spacy" on python for text documents lemmatization.
There are 500,000 documents having size up to 20 Mb of clean text.</p>
<p>The problem is the following: spacy memory consuming is growing in time till the whole memory is used.</p>
<h2>2 - BACKGROUND</h2>
<p>My hardware config... | <h1>Memory leaks with spacy</h1>
<p>Memory problems when processing large amounts of data seem to be a known issue, see some relevant github issues:</p>
<ul>
<li><a href="https://github.com/explosion/spaCy/issues/3623" rel="noreferrer">https://github.com/explosion/spaCy/issues/3623</a></li>
<li><a href="https://gith... | 950 |
spaCy | output of spacy convert command not compatible with spacy train command | https://stackoverflow.com/questions/55615335/output-of-spacy-convert-command-not-compatible-with-spacy-train-command | <p>I wanted to convert conllu format for Hindi to json using spacy convert and it is generating jsonl format. When I pass on the same .jsonl file to spacy train I am getting an error. If I pass a json file to the train command, it is working. Shouldn't the output of spacy convert be compatible with spacy train? </p>
... | <p>I had the same problem when outputting convertions as <em>default jsonl format</em>. Fixed by converting with file-type : json attribute e.g.</p>
<pre><code>python -m spacy convert lang_train.conllu output-folder --file-type json
</code></pre>
| 951 |
spaCy | Can not install SPACY successfully | https://stackoverflow.com/questions/76869787/can-not-install-spacy-successfully | <p>I tried to install spacy though conda with the command:</p>
<pre><code> conda install -c conda-forge spacy
</code></pre>
<p>The package was installed seemingly uneventfully. But when I tried to import spacy I got an exception.
It seems the module pydantic is not cooperating well. I am a bit surprised that during... | <p>In my case I directly installed <code>spacy</code> from PyPI, instead of <code>conda install</code> and it works fine.</p>
<pre><code>python -m pip install spacy
</code></pre>
<p>Kindly make sure you are inside the conda virtual env.</p>
| 952 |
spaCy | Tweek spacy spans | https://stackoverflow.com/questions/71481327/tweek-spacy-spans | <p>I am using spacy un some nlp project.</p>
<p>I have texts in which text like this appear:</p>
<pre><code> text='The car comprises 4 brakes 4.1, 4.2, 4.3 and 4.4 in fig. 5, all include an ESP system. This is shown in Fig. 6. Fig. 5 shows how the motors 56 and 57 are blocked. Besides the doors (44, 45) are painted blu... | <p>There is a <a href="https://spacy.io/usage/rule-based-matching" rel="nofollow noreferrer">chapter</a> in Spacy doc dedicated to matching based on rules. You can use Spacy to match spans based on "regex like" rules and also you can extend the pipeline to include your rules and for example recognize entities... | 953 |
spaCy | Installing spacy returns 'set_default_tensor_type' error | https://stackoverflow.com/questions/70102594/installing-spacy-returns-set-default-tensor-type-error | <p>In a Jupyter Notebook, using Python 3.9.9</p>
<p>I went to <a href="https://spacy.io/usage" rel="nofollow noreferrer">https://spacy.io/usage</a> and followed the instructions for installing Spacy</p>
<p>• MacOS/OSX</p>
<p>• conda</p>
<p>• virtual env</p>
<p>• English</p>
<p>• efficiency</p>
<pre class="lang-py prett... | <p>I had to updated pytorch</p>
<p>in your terminal, type:</p>
<pre><code>$! pip install --upgrade torch torchvision
</code></pre>
| 954 |
spaCy | How to get spaCy NER probability | https://stackoverflow.com/questions/46934523/how-to-get-spacy-ner-probability | <p>I want to combine spaCy's NER engine with a separate NER engine (a BoW model). I'm currently comparing outputs from the two engines, trying to figure out what the optimal combination of the two would be. Both perform decently, but quite often spaCy finds entities that the BoW engine misses, and vice versa. What I wo... | <p>Actually, there is an <a href="https://github.com/explosion/spaCy/issues/881" rel="noreferrer">issue</a> for that.</p>
<p>The author of the library, suggests there (among others) the following solution:</p>
<blockquote>
<ol>
<li>Beam search with global objective.
This is the standard solution: use a global o... | 955 |
spaCy | A checklist for Spacy optimization? | https://stackoverflow.com/questions/74181750/a-checklist-for-spacy-optimization | <p>I have been trying to understand how to systematically make Spacy run as fast as possible for a long time and I would like this post to become a wiki-style public post if possible.</p>
<p>Here is what I currently know, with subsidiary questions on each point:</p>
<p><strong>1. Space will run faster on faster hardwar... | <h1>Checklist</h1>
<p>The following checklist is focused on runtime performance optimization and not training (i.e. when one utilises existing <code>config.cfg</code> files loaded with the convenience wrapper <code>spacy.load()</code>, instead of training their own models and creating a new <code>config.cfg</code> file... | 956 |
spaCy | Don't know how to uninstall unwanted Spacy installation, model | https://stackoverflow.com/questions/53052868/dont-know-how-to-uninstall-unwanted-spacy-installation-model | <p>I have limited disk memory and want to know how to uninstall/remove files for spacy 2.xx under python 2.7 (I use python3 and think I've got spacy installed correctly for it). Ditto for the default model in my python3 install. Here's my terminal session:</p>
<pre><code>gw-mac-pro:~ gr$ pip install -U spacy
Collectin... | <p><em>spaCy</em> installs models as packages (via <code>pip</code>). That means you can uninstall them via <code>pip</code> as well:</p>
<pre><code>pip list
</code></pre>
<p>This shows you all the installed packages, including the <em>spaCy</em> models.</p>
<blockquote>
<p>…</p>
<p>en-core-web-sm 2.0.0</p... | 957 |
spaCy | Spacy cannot find model | https://stackoverflow.com/questions/66048470/spacy-cannot-find-model | <p>There are tickets or bugs across the internet on this and because there's Spacy 2.3 and 3.0 I can't tell which is relevant. I'm running 2.3 because moving to 3.0 is like moving to dojo 2.0. All that youtube watching is down the drain. Anyway, the following works:</p>
<pre><code>spacy.load(r'C:\Users\martingale.he... | <blockquote>
<p>How do I get spacy to do <code>spacy.load('en')</code> in 2.3?</p>
</blockquote>
<p>You can't. From <a href="https://spacy.io/usage/models#download:%7E:text=installation.-,IMPORTANT%20NOTE%20FOR%20V3.0" rel="nofollow noreferrer">the docs</a>:</p>
<blockquote>
<p>Note that as of spaCy v3.0, shortcut link... | 958 |
spaCy | SSL Certificate error while installing Spacy | https://stackoverflow.com/questions/68205676/ssl-certificate-error-while-installing-spacy | <p>I am facing the below error while installing Spacy.</p>
<pre><code>requests.exceptions.SSLError: HTTPSConnectionPool(host='raw.githubusercontent.com', port=443): Max retries exceeded with url: /explosion/spacy-models/master/compatibility.json (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_... | <p>I have fixed using this set of commands:</p>
<pre><code>pip install pip-system-certs
python -m spacy download it_core_news_sm
</code></pre>
<p>Ref: <a href="https://github.com/explosion/spaCy/discussions/5649" rel="noreferrer">https://github.com/explosion/spaCy/discussions/5649</a></p>
| 959 |
spaCy | Spacy CLI tools not functioning | https://stackoverflow.com/questions/69082919/spacy-cli-tools-not-functioning | <p>As the title says, I am unable to use the spacy cli tools. I get <code>No module named spacy</code> error when I try to run <code>python3 -m spacy download en_core_web_trf</code>.</p>
<p>I was able to install the sm, md and lg models a few days ago. But now it doesnt seem to be working. I have spacy v3 installed</p... | 960 | |
spaCy | Spacy download on Apple M1 chip | https://stackoverflow.com/questions/70658085/spacy-download-on-apple-m1-chip | <p>I'm in a MacBook Pro with M1 Pro chip, and I've built a Docker to install Tensorflow, spacy, etc.
My Dockerfile:</p>
<pre><code>FROM --platform=linux/x86_64 python:3.8
ENV PYTHONUNBUFFERED 1
RUN apt-get update && apt-get -y upgrade
RUN pip install --upgrade pip
RUN pip install TensorFlow==2.3.4
RUN pip ins... | 961 | |
spaCy | processing grammar using spaCY | https://stackoverflow.com/questions/48356424/processing-grammar-using-spacy | <p>I'm going to check for grammar in the sentences I give as input. If <strong>spaCy</strong> identifies <code>PRP</code> and <code>MD</code> and <code>NN</code> in a sentence then it will give me a text output</p>
<blockquote>
<p>there is a prp, md and nn in the sentence</p>
</blockquote>
<p>The problem is: how ca... | <p>If I understand correctly:</p>
<pre><code>In [34]: chk_set = set(['PRP','MD','NN'])
In [35]: chk_set.issubset(t.tag_ for t in nlp("I will go to the mall"))
Out[35]: True
In [36]: chk_set.issubset(t.tag_ for t in nlp("I will go"))
Out[36]: False
</code></pre>
<p><strong>UPDATE:</strong></p>
<blockquote>
<p>how... | 962 |
spaCy | Applying Spacy Parser to Pandas DataFrame w/ Multiprocessing | https://stackoverflow.com/questions/44395656/applying-spacy-parser-to-pandas-dataframe-w-multiprocessing | <p>Say I have a dataset, like</p>
<pre><code>iris = pd.DataFrame(sns.load_dataset('iris'))
</code></pre>
<p>I can use <code>Spacy</code> and <code>.apply</code> to parse a string column into tokens (my real dataset has >1 word/token per entry of course)</p>
<pre><code>import spacy # (I have version 1.8.2)
nlp = spac... | <p>Spacy is highly optimised and does the multiprocessing for you. As a result, I think your best bet is to take the data out of the Dataframe and pass it to the Spacy pipeline as a list rather than trying to use <code>.apply</code> directly.</p>
<p>You then need to the collate the results of the parse, and put this b... | 963 |
spaCy | How to fix spaCy en_model incompatible with current spaCy version (2.3.2)? | https://stackoverflow.com/questions/64035821/how-to-fix-spacy-en-model-incompatible-with-current-spacy-version-2-3-2 | <p>When I am running my NER model I am getting:</p>
<pre><code>UserWarning: [W031] Model 'en_model' (0.0.0) requires spaCy v2.2 and is incompatible with the current spaCy version (2.3.2)
</code></pre>
<p>Please advise how can I fix it?</p>
<p>Python 3.7.9, spaCy 2.3.2, Ubuntu 18.04.</p>
| <p>Solved by downgrading spaCy to 2.2.4.</p>
<pre><code>pip3 install spacy==2.2.4
</code></pre>
| 964 |
spaCy | How to install spacy? | https://stackoverflow.com/questions/79260748/how-to-install-spacy | <p>I am using trying to install spacy library using 'pip install -U spacy' in the command prompt (run as admin) in Windows-11 O.S., but it shows some error I don't understand. I am using Python 3.13.0, gcc 13.2.0 and make 4.4.1. What could be the problem? Or is there any other way to install spacy?</p>
<pre class="lang... | <p>I raised a git issue a couple of months back:</p>
<p><strong><a href="https://github.com/explosion/spaCy/issues/13658#issuecomment-2532080140" rel="nofollow noreferrer">https://github.com/explosion/spaCy/issues/13658#issuecomment-2532080140</a></strong></p>
<p><em>They are updating the build system across their pack... | 965 |
spaCy | trouble to install spaCy 3.0 on GoogleColab | https://stackoverflow.com/questions/68494390/trouble-to-install-spacy-3-0-on-googlecolab | <h2 id="background-hnaq">Background</h2>
<p>I'm woking on the following local environment and need to use spaCy 3.0 on GoogleColab.</p>
<p>However, it looks accepted to install spaCy after 3.0 because of python version.</p>
<pre><code>spaCy version 3.0.5
Python version 3.9.1
</code></pre... | <p>You can use <code>pip</code> to install spaCy, and specify version 3.1.1</p>
<pre><code>!pip install spacy==3.1.1
</code></pre>
<p>Then you can check the result.</p>
<pre><code>import spacy
print(spacy.__version__) # 3.1.1
</code></pre>
| 966 |
spaCy | spacy installation error (running cythonize failed) | https://stackoverflow.com/questions/41972099/spacy-installation-error-running-cythonize-failed | <p>So I was compiling spacy from source. I have cython v23.4 installed. when I run <code>pip install -e .</code> in the <code>spaCy</code> directory, I get this:
`Obtaining file:///home/nitish/spaCy
Complete output from command python setup.py egg_info:</p>
<pre><code>Error compiling Cython file:
-----------------... | <p>As you install from the local repository, you should install the requirements first.</p>
<pre><code>pip install -r requirements.txt
</code></pre>
<p>from the spaCy repository.</p>
<p>Do you have a specific reason for using the <code>-e</code> option? If not, I recommend to use <code>--user</code> instead.</p>
| 967 |
spaCy | Install SpaCy in a Jupyter Notebook | https://stackoverflow.com/questions/64268889/install-spacy-in-a-jupyter-notebook | <p>I try to install SpaCy for lemmatization, but it won't work...</p>
<p>First I install spacy:</p>
<pre><code>pip install -U spacy
</code></pre>
<p>Which leads to this results:</p>
<pre><code>Requirement already satisfied, skipping upgrade: murmurhash<1.1.0,>=0.28.0 in c:\users\danis\.conda\envs\python36\lib\sit... | <p>In order to load the model you need to download it first, if you are doing it on your local machine.(not on google colab). So after</p>
<pre><code>pip install -U spacy
</code></pre>
<p>you need to download using</p>
<pre><code>python -m spacy download de_core_news_sm
</code></pre>
<p>Then,</p>
<pre><code>nlp = spacy... | 968 |
spaCy | SpaCy lemmatizer removes capitalization | https://stackoverflow.com/questions/63693463/spacy-lemmatizer-removes-capitalization | <p>I would like to lemmatize some textual data in Hungarian language and encountered a strange feature in <code>spaCy</code>. The <code>token.lemma_</code> function works well in terms of lemmatization, however, it returns some of the sentences without first letter capitalization. This is quite annoying, as my next fun... | <p>Lowercasing is the expected behavior of spaCy's lemmatizer for non-proper-noun tokens.</p>
<p>One workaround is to check if each token is titlecased, and convert to original casing after lemmatizing (only applies to the first character).</p>
<pre><code>import spacy
nlp = spacy.load('en_core_web_sm')
text = 'This i... | 969 |
spaCy | What versions of spaCy suport en_vectors_web_lg? | https://stackoverflow.com/questions/67361527/what-versions-of-spacy-suport-en-vectors-web-lg | <p>I am trying to download en_vectors_web_lg, but keep getting the below error:</p>
<pre><code>ERROR: Could not install requirement en-vectors-web-lg==3.0.0 from https://github.com/explosion/spacy-models/releases/download/en_vectors_web_lg-3.0.0/en_vectors_web_lg-3.0.0-py3-none-any.whl#egg=en_vectors_web_lg==3.0.0 beca... | <p>The naming conventions changed in v3 and the equivalent model is <code>en_core_web_lg</code>. It includes vectors and you can install it like this:</p>
<pre><code>spacy download en_core_web_lg
</code></pre>
<p>I would not recommend downgrading to use the old vectors model unless you need to run old code.</p>
<p>If y... | 970 |
spaCy | Evaluation in a Spacy NER model | https://stackoverflow.com/questions/44827930/evaluation-in-a-spacy-ner-model | <p>I am trying to evaluate a trained NER Model created using <a href="https://spacy.io/docs/usage/training-ner" rel="noreferrer">spacy lib</a>.
Normally for these kind of problems you can use f1 score (a ratio between precision and recall). I could not find in the documentation an accuracy function for a trained NER m... | <p>You can find different metrics including F-score, recall and precision in <a href="https://github.com/explosion/spaCy/blob/master/spacy/scorer.py" rel="noreferrer">spaCy/scorer.py</a>.</p>
<p>This example shows how you can use it:</p>
<pre><code>import spacy
from spacy.gold import GoldParse
from spacy.scorer import ... | 971 |
spaCy | Spacy incorrectly identifying pronouns | https://stackoverflow.com/questions/75141938/spacy-incorrectly-identifying-pronouns | <p>When I try this code using Spacy, I get the desired result:</p>
<pre><code>import spacy
nlp = spacy.load("en_core_web_sm")
# example 1
test = "All my stuff is at to MyBOQ"
doc = nlp(test)
for word in doc:
if word.pos_ == 'PRON':
print(word.text)
</code></pre>
<p>The output shows <c... | <p>When running your code on my machine (Windows 11 64-bit, Python 3.10.9, spaCy 3.4.4), spaCy produces the following results for the text with and without the question mark:</p>
<pre class="lang-none prettyprint-override"><code> en_core_web_sm en_core_web_md en_core_web_trf
All my stu... | 972 |
spaCy | Spacy SpanGroup | https://stackoverflow.com/questions/68537075/spacy-spangroup | <p>I am trying to use spaCy's SpanGroup class, but the following commands both give a ModuleNotFoundError:</p>
<p><code>from spacy.tokens.span_group import SpanGroup</code> and
<code>from spacy.tokens import SpanGroup</code></p>
<p>I tried looking at the spaCy documentation, but their command wasn't working. Does someo... | <p>The code in <a href="https://spacy.io/api/spangroup#_title" rel="nofollow noreferrer">the docs</a> works for me.</p>
<pre><code>from spacy.tokens import SpanGroup
</code></pre>
<p>Does that give you an error?</p>
| 973 |
spaCy | Spacy Permission Error 13 | https://stackoverflow.com/questions/48165486/spacy-permission-error-13 | <p>I am getting Permission error 13 when trying to save a trained model in spacy. I have tried changing the directory as well. I am trying to reproduce this example given <a href="https://spacy.io/usage/training#example-new-entity-typetrain_new_entity_type.py" rel="nofollow noreferrer">here</a>, to train custom entitie... | <p>I think that it can be that the path you use <code>/model</code> is seen as an absolute path, so either exits a <code>/model</code> directory writeable by the user or you can try to use a path like <code>./model</code> which is a relative path</p>
| 974 |
spaCy | Spacy 3.0.1 Accuracy prediction | https://stackoverflow.com/questions/66637485/spacy-3-0-1-accuracy-prediction | <p>How to test accuracy of a spacy pretrained model in version 3.0.1. I want to see my output how accurate my tested model is predicted.This the code below for spacy version 2 but it doesn't work in spacy version 3.can somone tell me the code on spacy version 3.</p>
<pre><code> from spacy.gold import GoldParse
from sp... | <p>Personnally i had used this method, and i wish it will help you in your work:
In your case, I think:</p>
<pre><code>from spacy.training import Example
#get test data
test_data = [
("Trump says he's answered Mueller's Russia inquiry questions \u2013
live",{"entities":[[0,5,"PERSON&... | 975 |
spaCy | Custom sentence segmentation using Spacy | https://stackoverflow.com/questions/52205475/custom-sentence-segmentation-using-spacy | <p>I am new to Spacy and NLP. I'm facing the below issue while doing sentence segmentation using Spacy.</p>
<p>The text I am trying to tokenise into sentences contains numbered lists (with space between numbering and actual text), like below.</p>
<pre class="lang-py prettyprint-override"><code>import spacy
nlp = spacy.... | <p>When you use a pretrained model with spacy, the sentences get splitted based on training data that were provided during the training procedure of the model.</p>
<p>Of course, there are cases like yours, that may somebody want to use a custom sentence segmentation logic. This is possible by adding a component to spa... | 976 |
spaCy | Training spaCy - NameError | https://stackoverflow.com/questions/68048737/training-spacy-nameerror | <p>I need to train a spaCy model to improve the accuracy to identify products. I'm struggling with training my spacy model. I have the following code:</p>
<pre><code>TRAIN_DATA = [('..., {'entities': [(36,55,'PRODUCT')]})]
nlp = spacy.load("en_core_web_lg")
ner = nlp.get_pipe("ner")
optimizer = nlp... | <p>It's hot here...
thanks for the hint I missed importing:
from spacy.training import Example</p>
<p>when moving the code from Jupyter to Visual Studio Code for the deployment</p>
| 977 |
spaCy | SpaCy: how to load Google news word2vec vectors? | https://stackoverflow.com/questions/42094180/spacy-how-to-load-google-news-word2vec-vectors | <p>I've tried several methods of loading the google news word2vec vectors (<a href="https://code.google.com/archive/p/word2vec/" rel="noreferrer">https://code.google.com/archive/p/word2vec/</a>):</p>
<pre><code>en_nlp = spacy.load('en',vector=False)
en_nlp.vocab.load_vectors_from_bin_loc('GoogleNews-vectors-negative30... | <p>For spacy 1.x, load Google news vectors into gensim and convert to a new format (each line in .txt contains a single vector: string, vec):</p>
<pre><code>from gensim.models.word2vec import Word2Vec
from gensim.models import KeyedVectors
model = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin',... | 978 |
spaCy | "python" unable to import spacy and download en_core_web_sm | https://stackoverflow.com/questions/76319917/python-unable-to-import-spacy-and-download-en-core-web-sm | <p><strong>What I want to achieve:</strong></p>
<p>Import spacy and use it.</p>
<p><em><strong>What I've tried:</strong></em></p>
<p>When I try to import spacy on python I get <strong>ImportError: cannot import name util</strong> error (detail on error1)</p>
<p>Spacy is sucessfully installed to my device.</p>
<p><a hre... | <p>This has been reported. See the suggested workaround: <a href="https://github.com/explosion/spaCy/issues/12659" rel="nofollow noreferrer">https://github.com/explosion/spaCy/issues/12659</a>.</p>
| 979 |
spaCy | Instaling SpaCy for Anaconda | https://stackoverflow.com/questions/61259713/instaling-spacy-for-anaconda | <p>Hi guys I'm having a problem with installing SpaCy on Windows/Anaconda.
I was trying:</p>
<p><strong>conda install -c conda-forge spacy</strong></p>
<p>And I'm getting an error:</p>
<pre class="lang-none prettyprint-override"><code>Collecting package metadata (repodata.json): done
Solving environment: failed with... | 980 | |
spaCy | Use spacy on pretokenized text | https://stackoverflow.com/questions/59115914/use-spacy-on-pretokenized-text | <p>I want to use spacy for processing an already pre-tokenized text. Parsing a list of tokens to spacy does not work.</p>
<pre class="lang-py prettyprint-override"><code>import spacy
nlp = spacy.load("en_core_web_sm")
nlp(["This", "is", "a", "sentence"])
</code></pre>
<p>This gives a TypeError (which makes sense):
<c... | <p>You can use this method:</p>
<pre class="lang-py prettyprint-override"><code>tokens = ["This", "is", "a", "sentence"]
sentence = nlp.tokenizer.tokens_from_list(tokens)
print(sentence)
</code></pre>
<pre><code>This is a sentence
</code></pre>
| 981 |
spaCy | Blank lemmatization using spacy | https://stackoverflow.com/questions/70147866/blank-lemmatization-using-spacy | <p>How to use lemmatization in Spacy? I try with this code but the output is blank. My spacy ver. 3.2.0</p>
<pre><code>from spacy.lang.id import Indonesian
nlp = Indonesian()
def tokenizer(text):
return [token.lemma_.lower() for token in nlp(text) if not token.is_stop and not token.is_punct]
docs = [
'Saya ... | <p>You need to configure the <a href="https://spacy.io/usage/linguistic-features#lemmatizer-lookup" rel="nofollow noreferrer">lookup lemmatizer</a>. If you install <code>spacy-lookups-data</code> then you can do that like this:</p>
<pre><code>nlp = Indonesian()
nlp.add_pipe("lemmatizer", config={"mode&qu... | 982 |
spaCy | KeyError in spaCy GoldParse | https://stackoverflow.com/questions/47807189/keyerror-in-spacy-goldparse | <p>The following code fragment (modified from spaCy sample code) generates a KeyError that I just can't figure out:</p>
<pre><code>import en_core_web_sm
from spacy.gold import GoldParse
nlp = en_core_web_sm.load()
nlp.entity.add_label('ACCT')
TRAIN_DATA = [
("Exxon opened a new processing facility", {
"... | <p>I don't know how the spaCy <a href="https://github.com/explosion/spaCy/blob/v1.9.0/examples/training/train_new_entity_type.py" rel="nofollow noreferrer">sample code</a> ever worked, but the <code>GoldParse</code> method wants <code>entities</code> to be a <code>list</code>, not a <code>dict</code>. Changing the line... | 983 |
spaCy | spacy python package no longer runs | https://stackoverflow.com/questions/75978880/spacy-python-package-no-longer-runs | <p>Running python 3.11.3 on macos, Intel.</p>
<p>I had spacy working fine. I then decided to try adding gpu support with: <code>pip install -U 'spacy[cuda113]'</code> but started getting errors.</p>
<p>I uninstalled with <code>pip uninstall 'spacy[cuda113]'</code> and then reinstalled spacy with just <code>pip install ... | <p>I'm not quite sure how/why these commands fixed the issue, but they did:</p>
<pre><code>pip uninstall spacy
pip uninstall spacy_legacy
pip uninstall spacy_alignments
pip uninstall spacy_loggers
pip uninstall pydantic
pip install 'pydantic<1.8'
pip install spacy
pip uninstall pydantic
pip install pydantic
pip inst... | 984 |
spaCy | spacy Arabic word2vector | https://stackoverflow.com/questions/75565318/spacy-arabic-word2vector | <p>i try to arabic vector with spacy, so i try code from this github
<a href="https://github.com/bakrianoo/aravec/blob/master/aravec-with-spacy.ipynb" rel="nofollow noreferrer">https://github.com/bakrianoo/aravec/blob/master/aravec-with-spacy.ipynb</a></p>
<p>when i use this code</p>
<pre><code>!python -m spacy init-m... | <p>Can you try this solution.</p>
<pre><code>!python -m spacy init vectors ar ./spacyModel/spacy.aravec.model ./spacyModel/aravec.txt.gz
</code></pre>
<p>According to this information (<a href="https://github.com/explosion/spaCy/discussions/7509" rel="nofollow noreferrer">https://github.com/explosion/spaCy/discussions/... | 985 |
spaCy | Issue with install Spacy | https://stackoverflow.com/questions/50837733/issue-with-install-spacy | <p>Runing the command in the instruction:</p>
<pre><code>pip install -U spacy
</code></pre>
<p>It fails to build wheel for Building wheels for collected packages: spacy, murmurhash, cymem, preshed, thinc, ujson, regex, cytoolz</p>
<p>This is the error shown on the terminal.</p>
<pre><code> Running setup.py bdist_w... | <p>The best way to download Spacy and work with it is to download it manually and link it. Below command is used to download it and link it to your python libraries:</p>
<p>Command to download it:</p>
<pre><code>pip install https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_s... | 986 |
spaCy | Error while executing "python -m spacy download en_core_web_sm" in spacy python | https://stackoverflow.com/questions/76006334/error-while-executing-python-m-spacy-download-en-core-web-sm-in-spacy-python | <p>I am trying to load "en_core_web_sm" in spacy but getting the following error</p>
<p><em>Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))</em></p>
<pre><code>import spacy
from spacy import displacy
from spacy import tokeniz... | <p>Downloading whl file from here <a href="https://github.com/explosion/spacy-models/releases/tag/en_core_web_sm-3.1.0" rel="nofollow noreferrer">spacy</a></p>
<p>and running the command</p>
<pre><code>pip install en_core_web_sm-3.1.0-py3-none-any.whl
</code></pre>
<p>did the trick</p>
| 987 |
spaCy | spaCy and scikit-learn vectorizer | https://stackoverflow.com/questions/45196312/spacy-and-scikit-learn-vectorizer | <p>I wrote a lemma tokenizer using spaCy for scikit-learn based on their <a href="http://scikit-learn.org/stable/modules/feature_extraction.html" rel="noreferrer">example</a>, it works OK standalone:</p>
<pre><code>import spacy
from sklearn.feature_extraction.text import TfidfVectorizer
class LemmaTokenizer(object):
... | <p>You are wasting time by running Spacy for each parameter setting in the grid. The memory overhead is also significant. You should run all data through Spacy once and save it to disk, then use a simplified vectoriser that reads in pre-lemmatised data. Look at the <code>tokenizer</code>, <code>analyser</code> and <cod... | 988 |
spaCy | Python - cannot install spaCy | https://stackoverflow.com/questions/51501274/python-cannot-install-spacy | <p>I am trying to install spaCy on a Mac (OSX El Capitain). I am running python 2.7, have pip 18.0 and setuptools 40.0.</p>
<p>Whenever I run 'sudo pip install spacy', I get the following:</p>
<pre><code>Installing collected packages: numpy, murmurhash, cymem, preshed, msgpack, msgpack-numpy, toolz, cytoolz, wrapt, p... | 989 | |
spaCy | Build vocab using spacy | https://stackoverflow.com/questions/66838185/build-vocab-using-spacy | <p>I'm using spacy tokenizer to tokenize my data, and then build vocab.</p>
<p>This is my code:</p>
<pre><code>import spacy
nlp = spacy.load("en_core_web_sm")
def build_vocab(docs, max_vocab=10000, min_freq=3):
stoi = {'<PAD>':0, '<UNK>':1}
itos = {0:'<PAD>', 1:'<UNK>'}
word_freq =... | <p>There are a couple of things you can do to make this faster.</p>
<pre><code>import spacy
from collections import Counter
def build_vocab(texts, max_vocab=10000, min_freq=3):
nlp = spacy.blank("en") # just the tokenizer
wc = Counter()
for doc in nlp.pipe(texts):
for word in doc:
... | 990 |
spaCy | spacy split sentences with abbreviations | https://stackoverflow.com/questions/53968330/spacy-split-sentences-with-abbreviations | <p>spaCy splits a sentence incorrectly when there are dots for abbreviations.</p>
<pre><code>import spacy
tool = spacy.load('en')
x = tool('It starts at 9:00 a.m. Eastern Standard Time.')
list(x.sents)
</code></pre>
<p>produces two sentences instead of one. How do I do this correctly?</p>
| <p>If you are using the standard English models, <code>en_core_web_sm</code> or <code>en_core_web_md</code> or <code>en_core_web_lg</code>, the most common abbreviations like that one should be already handled:</p>
<pre><code>>>> import spacy
>>> nlp = spacy.load('en_core_web_sm')
>>> doc = ... | 991 |
spaCy | How to extract tag attributes using Spacy | https://stackoverflow.com/questions/53755559/how-to-extract-tag-attributes-using-spacy | <p>I tried to get the morphological attributes of the verb using Spacy like below:</p>
<pre><code>import spacy
from spacy.lang.it.examples import sentences
nlp = spacy.load('it_core_news_sm')
doc = nlp('Ti è piaciuto il film?')
token = doc[2]
nlp.vocab.morphology.tag_map[token.tag_]
</code></pre>
<p>output was:</p>
... | <p>The <code>nlp.vocab.morphology.tag_map</code> maps from the detailed tag to the dict with simpler tag, so you just need to skip that step and inspect the tag directly:</p>
<pre><code>import spacy
nlp = spacy.load('it')
doc = nlp('Ti è piaciuto il film?')
print(doc[2].tag_)
</code></pre>
<p>should return</p>
<bloc... | 992 |
spaCy | Problem initializing experimental spacy coref | https://stackoverflow.com/questions/78732626/problem-initializing-experimental-spacy-coref | <p>Using the documentation here (<a href="https://spacy.io/api/coref" rel="nofollow noreferrer">https://spacy.io/api/coref</a>) to try and work a coreference resolution problem. I run into problems immediately when trying to add the pipe:</p>
<pre><code>nlp = spacy.load("en_core_web_md")
coref = nlp.add_pipe(... | 993 | |
spaCy | SpaCy permission denied | https://stackoverflow.com/questions/53200628/spacy-permission-denied | <p>I sorta have two issues, and I only mention both because I think they might be related.</p>
<p><strong>Problem 1:</strong></p>
<p>I believe I have two versions of Python3 downloaded (one through Anaconda) because when I run</p>
<pre><code>$ pip3 --version
</code></pre>
<p>I get</p>
<pre><code>pip 9.0.1 from /Li... | <h1>To solve problem 2 (Windows);</h1>
<ol>
<li>Log into Windows as an administrator.</li>
<li>Right-click on the file or folder you want to change permissions for. </li>
<li>Select "Properties."</li>
<li>Click the "Security" tab.</li>
<li>Click the "Edit" button.</li>
<li>Click the "Add" button to add a new user or g... | 994 |
spaCy | ConnectTimeout Error while downloading spacy models | https://stackoverflow.com/questions/76789756/connecttimeout-error-while-downloading-spacy-models | <p>I started using spacy (3.6.0) recently. I understand that I have to download pre-trained models every time I re-start my kernel. It worked well for a couple of times with</p>
<p><code>!python -m spacy download en_core_web_lg</code></p>
<p>Then it started giving me errors. A little bit of research helped me find an a... | 995 | |
spaCy | spacy sentence tokenization error on Hebrew | https://stackoverflow.com/questions/48572541/spacy-sentence-tokenization-error-on-hebrew | <p>Trying to use spacy sentence tokenization for Hebrew.</p>
<pre><code>import spacy
nlp = spacy.load('he')
doc = nlp(text)
sents = list(doc.sents)
</code></pre>
<p>I get:</p>
<pre><code> Warning: no model found for 'he'
Only loading the 'he' tokenizer.
Traceback (most recent call last):
...
sents ... | <p>spaCy's <a href="https://spacy.io/usage/models#alpha-support" rel="noreferrer">Hebrew coverage</a> is currently quite minimal. It currently only has <em>word</em> tokenization for Hebrew, which roughly splits on white space with some extra rules and exceptions. The <em>sentence</em> tokenization/boundary detection t... | 996 |
spaCy | SpaCy: Person entities missing | https://stackoverflow.com/questions/49532259/spacy-person-entities-missing | <p>I have some issues with spaCy missing Person entities. Below is an example when it seems like SpaCy is going blind when the name is preceded with certain titles. When you remove <code>Labour MP</code> (commented line) it recognises the name otherwise returns an empty list.</p>
<pre><code>import spacy
from spacy.en ... | <p>I tried your code with Spacy Version 2.0.7 and it does give "Luciana Berger" as an entity for the sentence </p>
<p>I am getting this list <code>['Luciana Berger']</code> for sentence <code>"In a recent tweet, Labour MP Luciana Berger sought clarification..."</code></p>
<p>Also for other sentence, it gives "James M... | 997 |
spaCy | Get position of word in sentence with spacy | https://stackoverflow.com/questions/46049612/get-position-of-word-in-sentence-with-spacy | <p>I'm aware of the basic spacy workflow for getting various attributes from a document, however I can't find a built in function to return the position (start/end) of a word which is part of a sentence.</p>
<p>Would anyone know if this is possible with Spacy?</p>
| <p>These are available as attributes of the tokens in the sentences.
<a href="https://spacy.io/docs/api/token#attributes" rel="noreferrer">Doc</a> says:</p>
<blockquote>
<p>idx int The character offset of the token within the parent document.</p>
<p>i int The index of the token within the parent document.</p>... | 998 |
spaCy | Spacy Pipeline? | https://stackoverflow.com/questions/38986235/spacy-pipeline | <p>So lately I've been playing around with a WikiDump.
I preprocessed it and trained it on Word2Vec + Gensim</p>
<p>Does anyone know if there is only one script within Spacy that would generate
tokenization, sentence recognition, part of speech tagging, lemmatization, dependency parsing, and named entity recognition a... | <p>Spacy gives you all of that with just using <code>en_nlp = spacy.load('en'); doc=en_nlp(sentence)</code>. The <a href="https://spacy.io/docs/#getting-started" rel="noreferrer">documentation</a> gives you details about how to access each of the elements.</p>
<p>An example is given below:</p>
<pre><code>In [1]: impo... | 999 |
matplotlib | How do I change the size of figures drawn with Matplotlib? | https://stackoverflow.com/questions/332289/how-do-i-change-the-size-of-figures-drawn-with-matplotlib | <p>How do I change the size of figure drawn with Matplotlib?</p>
| <p><a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html" rel="noreferrer"><code>figure</code></a> tells you the call signature:</p>
<pre><code>from matplotlib.pyplot import figure
figure(figsize=(8, 6), dpi=80)
</code></pre>
<p><code>figure(figsize=(1,1))</code> would create an inch-by-inch... | 1,000 |
matplotlib | Save plot to image file instead of displaying it | https://stackoverflow.com/questions/9622163/save-plot-to-image-file-instead-of-displaying-it | <p>This displays the figure in a GUI:</p>
<pre><code>import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
</code></pre>
<p>But how do I instead save the figure to a file (e.g. foo.png)?</p>
| <p>When using <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html" rel="noreferrer"><code>matplotlib.pyplot.savefig</code></a>, the file format can be specified by the extension:</p>
<pre><code>from matplotlib import pyplot as plt
plt.savefig('foo.png')
plt.savefig('foo.pdf')
</code></pre... | 1,001 |
matplotlib | How to put the legend outside the plot | https://stackoverflow.com/questions/4700614/how-to-put-the-legend-outside-the-plot | <p>I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, as the size of the figure gets reduced.</p>
<ol>
<li>I want to keep the legend box outside the plot area (I want the legend to be outside at the ri... | <ul>
<li>You can make the legend text smaller by specifying <code>set_size</code> of <code>FontProperties</code>.</li>
<li>Resources:
<ul>
<li><a href="https://matplotlib.org/tutorials/intermediate/legend_guide.html#legend-guide" rel="noreferrer">Legend guide</a></li>
<li><a href="https://matplotlib.org/api/legend_api.... | 1,002 |
matplotlib | How to change the font size on a matplotlib plot | https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot | <p>How does one change the font size for all elements (ticks, labels, title) on a matplotlib plot?</p>
<p>I know how to change the tick label sizes, this is done with:</p>
<pre><code>import matplotlib
matplotlib.rc('xtick', labelsize=20)
matplotlib.rc('ytick', labelsize=20)
</code></pre>
<p>But how does one chang... | <p>From the <a href="https://matplotlib.org/stable/api/matplotlib_configuration_api.html#matplotlib.rc" rel="noreferrer">matplotlib documentation</a>,</p>
<pre><code>font = {'family' : 'normal',
'weight' : 'bold',
'size' : 22}
matplotlib.rc('font', **font)
</code></pre>
<p>This sets the font of all i... | 1,003 |
matplotlib | Purpose of "%matplotlib inline" | https://stackoverflow.com/questions/43027980/purpose-of-matplotlib-inline | <p>What exactly is the use of <code>%matplotlib inline</code>?</p>
| <p><code>%matplotlib</code> is a <a href="http://ipython.readthedocs.io/en/stable/interactive/tutorial.html#magics-explained" rel="noreferrer"><em>magic function</em></a> in IPython. I'll quote the relevant documentation here for you to read for convenience:</p>
<blockquote>
<p>IPython has a set of predefined ‘magic... | 1,004 |
matplotlib | How to make IPython notebook matplotlib plot inline | https://stackoverflow.com/questions/19410042/how-to-make-ipython-notebook-matplotlib-plot-inline | <p>I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.</p>
<p>I cannot get matplotlib graphics to show up inline.</p>
<pre><code>import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
</code></pre>
<p>I have also tried <code>%pylab inline</code> and ... | <p>I used <code>%matplotlib inline</code> in the first cell of the notebook and it works. I think you should try:</p>
<pre><code>%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
</code></pre>
<p>You can also always start all your IPython kernels in inline mode by default by set... | 1,005 |
matplotlib | When to use cla(), clf() or close() for clearing a plot | https://stackoverflow.com/questions/8213522/when-to-use-cla-clf-or-close-for-clearing-a-plot | <p>Matplotlib offers these functions:</p>
<pre class="lang-py prettyprint-override"><code>cla() # Clear axis
clf() # Clear figure
close() # Close a figure window
</code></pre>
<p>When should I use each function and what exactly does it do?</p>
| <p>They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the <code>Figure</code> class. I will discuss both cases below.</p>
<h2>pyplot inter... | 1,006 |
matplotlib | How do I set the figure title and axes labels font size? | https://stackoverflow.com/questions/12444716/how-do-i-set-the-figure-title-and-axes-labels-font-size | <p>I am creating a figure in Matplotlib like this:</p>
<pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.savefig('test.jpg')
</code></pre>
<p>I want to specify font sizes for th... | <p>Functions dealing with text like <code>label</code>, <code>title</code>, etc. accept parameters same as <a href="http://matplotlib.org/users/text_props.html" rel="noreferrer"><code>matplotlib.text.Text</code></a>. For the font size you can use <code>size/fontsize</code>:</p>
<pre><code>from matplotlib import pyplot... | 1,007 |
matplotlib | Changing the tick frequency on the x or y axis | https://stackoverflow.com/questions/12608788/changing-the-tick-frequency-on-the-x-or-y-axis | <p>I am trying to fix how python plots my data. Say:</p>
<pre class="lang-py prettyprint-override"><code>x = [0, 5, 9, 10, 15]
y = [0, 1, 2, 3, 4]
matplotlib.pyplot.plot(x, y)
matplotlib.pyplot.show()
</code></pre>
<p>The x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?</p>
| <p>You could explicitly set where you want to tick marks with <code>plt.xticks</code>:</p>
<pre><code>plt.xticks(np.arange(min(x), max(x)+1, 1.0))
</code></pre>
<hr>
<p>For example,</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arang... | 1,008 |
matplotlib | How do I change the figure size with subplots? | https://stackoverflow.com/questions/14770735/how-do-i-change-the-figure-size-with-subplots | <p>How do I increase the figure size for <a href="https://matplotlib.org/2.0.2/examples/pylab_examples/subplots_demo.html" rel="noreferrer">this figure</a>?</p>
<p>This does nothing:</p>
<pre class="lang-py prettyprint-override"><code>f.figsize(15, 15)
</code></pre>
<p>Example code from the link:</p>
<pre class="lang-p... | <p>Use <a href="https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.set_figwidth" rel="noreferrer"><code>.set_figwidth</code></a> and <a href="https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.set_figheight" rel="noreferrer"><code>.set_figheight</code></a> on the <a href=... | 1,009 |
matplotlib | pyplot scatter plot marker size | https://stackoverflow.com/questions/14827650/pyplot-scatter-plot-marker-size | <p>In the pyplot document for scatter plot:</p>
<pre class="lang-py prettyprint-override"><code>matplotlib.pyplot.scatter(x, y, s=20, c='b', marker='o', cmap=None, norm=None,
vmin=None, vmax=None, alpha=None, linewidths=None,
faceted=True, verts=None, hold=Non... | <p>This can be a somewhat confusing way of defining the size but you are basically specifying the <em>area</em> of the marker. This means, to double the width (or height) of the marker you need to increase <code>s</code> by a factor of 4. [because A = W<em>H => (2W)</em>(2H)=4A]</p>
<p>There is a reason, however, th... | 1,010 |
matplotlib | How to remove axis, legends, and white padding | https://stackoverflow.com/questions/9295026/how-to-remove-axis-legends-and-white-padding | <p>I would like to apply colormap to an image, and write the resulting image, without using axes, labels, titles, or anything automatically added by matplotlib. Here is what I did:</p>
<pre><code>def make_image(inputname,outputname):
data = mpimg.imread(inputname)[:,:,0]
fig = plt.imshow(data)
fig.set_cmap(... | <p>The <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.axis.html" rel="noreferrer"><code>axis('off')</code></a> method resolves one of the problems more succinctly than separately changing each axis and border. It still leaves the white space around the border however. Adding <code>bbox_inches='tig... | 1,011 |
matplotlib | How to set the axis limits in Matplotlib? | https://stackoverflow.com/questions/3777861/how-to-set-the-axis-limits-in-matplotlib | <p>I need help with setting the limits of y-axis on matplotlib. Here is the code that I tried, unsuccessfully.</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
plt.figure(1, figsize = (8.5,11))
plt.suptitle('plot title')
ax = []
aPlot = plt.subplot(321, axisbg = 'w', title = "Ye... | <p>Get current axis via <code>plt.gca()</code>, and then set its limits:</p>
<pre><code>ax = plt.gca()
ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])
</code></pre>
| 1,012 |
matplotlib | How to adjust padding with cutoff or overlapping labels | https://stackoverflow.com/questions/6774086/how-to-adjust-padding-with-cutoff-or-overlapping-labels | <h2>Updated MRE with subplots</h2>
<ul>
<li>I'm not sure of the usefulness of the original question and MRE. The margin padding seems to be properly adjusted for large x and y labels.</li>
<li>The issue is reproducible with subplots.</li>
<li>Using <code>matplotlib 3.4.2</code></li>
</ul>
<pre class="lang-py prettyprin... | <p>Use:</p>
<pre><code>import matplotlib.pyplot as plt
plt.gcf().subplots_adjust(bottom=0.15)
# alternate option without .gcf
plt.subplots_adjust(bottom=0.15)
</code></pre>
<p>to make room for the label, where <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.gcf.html" rel="noreferrer"><code>plt.gc... | 1,013 |
matplotlib | Rotate axis tick labels | https://stackoverflow.com/questions/10998621/rotate-axis-tick-labels | <p>I can't figure out how to rotate the text on the X Axis. Its a time stamp, so as the number of samples increase, they get closer and closer until they overlap. I'd like to rotate the text 90 degrees so as the samples get closer together, they aren't overlapping.</p>
<p>Below is what I have, it works fine with the... | <p>This works for me:</p>
<pre><code>plt.xticks(rotation=90)
</code></pre>
| 1,014 |
matplotlib | Hiding axis text in matplotlib plots | https://stackoverflow.com/questions/2176424/hiding-axis-text-in-matplotlib-plots | <p>I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.</p>
<p>This may be vague, b... | <p>Instead of hiding each element, you can hide the whole axis:</p>
<pre><code>frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)
</code></pre>
<p>Or, you can set the ticks to an empty list:</p>
<pre><code>frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])
... | 1,015 |
matplotlib | Why do many examples use `fig, ax = plt.subplots()` | https://stackoverflow.com/questions/34162443/why-do-many-examples-use-fig-ax-plt-subplots | <p>I'm learning to use <code>matplotlib</code> by studying examples, and a lot of examples seem to include a line like the following before creating a single plot...</p>
<pre><code>fig, ax = plt.subplots()
</code></pre>
<p>Here are some examples...</p>
<ul>
<li><a href="https://stackoverflow.com/questions/11244514/m... | <p><code>plt.subplots()</code> is a function that returns a tuple containing a figure and axes object(s). Thus when using <code>fig, ax = plt.subplots()</code> you unpack this tuple into the variables <code>fig</code> and <code>ax</code>. Having <code>fig</code> is useful if you want to change figure-level attributes o... | 1,016 |
matplotlib | Plot logarithmic axes | https://stackoverflow.com/questions/773814/plot-logarithmic-axes | <p>I want to plot a graph with one logarithmic axis using matplotlib.</p>
<p>Sample program:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)] # exponential
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
line, = ax.plot(a, color='blue', lw=2)
plt... | <p>You can use the <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_yscale.html" rel="noreferrer"><code>Axes.set_yscale</code></a> method. That allows you to change the scale after the <code>Axes</code> object is created. That would also allow you to build a control to let the user pick the s... | 1,017 |
matplotlib | How to change legend fontsize with matplotlib.pyplot | https://stackoverflow.com/questions/7125009/how-to-change-legend-fontsize-with-matplotlib-pyplot | <p>Simple question here: I'm trying to get the size of my legend using <code>matplotlib.pyplot</code> to be smaller (i.e., the text to be smaller). The code I'm using goes something like this:</p>
<pre><code>plot.figure()
plot.scatter(k, sum_cf, color='black', label='Sum of Cause Fractions')
plot.scatter(k, data[:, 0... | <p>You can set an individual font size for the legend by adjusting the <code>prop</code> keyword. </p>
<pre><code>plot.legend(loc=2, prop={'size': 6})
</code></pre>
<p>This takes a dictionary of keywords corresponding to <code>matplotlib.font_manager.FontProperties</code> properties. See the <a href="http://matplotli... | 1,018 |
matplotlib | What does the argument mean in fig.add_subplot(111)? | https://stackoverflow.com/questions/3584805/what-does-the-argument-mean-in-fig-add-subplot111 | <p>Sometimes I come across code such as this:</p>
<pre><code>import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = plt.figure()
fig.add_subplot(111)
plt.scatter(x, y)
plt.show()
</code></pre>
<p>Which produces:</p>
<p><img src="https://i.sstatic.net/yCOG3.png" alt="Example plot produced by ... | <p>These are subplot grid parameters encoded as a single integer. For example, "111" means "1x1 grid, first subplot" and "234" means "2x3 grid, 4th subplot".</p>
<p>Alternative form for <code>add_subplot(111)</code> is <code>add_subplot(1, 1, 1)</code>.</p>
| 1,019 |
matplotlib | "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm | https://stackoverflow.com/questions/56656777/userwarning-matplotlib-is-currently-using-agg-which-is-a-non-gui-backend-so | <p>I am trying to plot a simple graph using pyplot, e.g.:</p>
<pre><code>import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()
</code></pre>
<p>but the figure does not appear and I get the following message:</p>
<pre><code>UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so can... | <h3>Solution 1: is to install the GUI backend <code>tk</code></h3>
<p>I found a solution to my problem (thanks to the help of <a href="https://stackoverflow.com/users/4124317/importanceofbeingernest">ImportanceOfBeingErnest</a>).</p>
<p>All I had to do was to install <code>tkinter</code> through the Linux bash terminal... | 1,020 |
matplotlib | Reverse colormap in matplotlib | https://stackoverflow.com/questions/3279560/reverse-colormap-in-matplotlib | <p>I would like to know how to simply reverse the color order of a given colormap in order to use it with plot_surface.</p>
| <p>The standard colormaps also all have reversed versions. They have the same names with <code>_r</code> tacked on to the end. (<a href="https://matplotlib.org/stable/gallery/color/colormap_reference.html#reversed-colormaps" rel="noreferrer">Documentation here.</a>)</p>
| 1,021 |
matplotlib | Improve subplot size/spacing with many subplots | https://stackoverflow.com/questions/6541123/improve-subplot-size-spacing-with-many-subplots | <p>I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved using <code>savefig</code> and viewed on a webpage, so I don't care how tall the final image is, as long as the subplots are spaced so they don't overlap.</p>
<p>No matter how big I allow the figure to be, the subplo... | <p>Please review <a href="https://matplotlib.org/stable/users/explain/axes/tight_layout_guide.html" rel="noreferrer">matplotlib: Tight Layout guide</a> and try using <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tight_layout.html" rel="noreferrer"><code>matplotlib.pyplot.tight_layout</code></a>, ... | 1,022 |
matplotlib | How to change the figure size of a seaborn axes or figure level plot | https://stackoverflow.com/questions/31594549/how-to-change-the-figure-size-of-a-seaborn-axes-or-figure-level-plot | <p>How do I change the size of my image so it's suitable for printing?</p>
<p>For example, I'd like to use an A4 paper, whose dimensions are 11.7 inches by 8.27 inches in landscape orientation.</p>
| <p>You need to create the matplotlib Figure and Axes objects ahead of time, specifying how big the figure is:</p>
<pre><code>from matplotlib import pyplot
import seaborn
import mylib
a4_dims = (11.7, 8.27)
df = mylib.load_data()
fig, ax = pyplot.subplots(figsize=a4_dims)
seaborn.violinplot(ax=ax, data=df, **violin_o... | 1,023 |
matplotlib | Adding a matplotlib legend | https://stackoverflow.com/questions/19125722/adding-a-matplotlib-legend | <p>How can one create a legend for a line graph in Matplotlib's PyPlot without creating any extra variables?</p>
<p>Please consider the graphing script below:</p>
<pre class="lang-py prettyprint-override"><code>if __name__ == '__main__':
PyPlot.plot(length, bubble, 'b-',
length, ins, 'r-',
... | <p>Add a <code>label=</code> to each of your <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot" rel="noreferrer"><code>plot()</code></a> calls, and then call <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend" rel="noreferrer"><code>legend(loc='upper left')</code></a>.</... | 1,024 |
matplotlib | How to change plot background color? | https://stackoverflow.com/questions/14088687/how-to-change-plot-background-color | <p>I am making a scatter plot in matplotlib and need to change the background of the actual plot to black. I know how to change the face color of the plot using:</p>
<pre><code>fig = plt.figure()
fig.patch.set_facecolor('xkcd:mint green')
</code></pre>
<p><a href="https://i.sstatic.net/UN6YB.png" rel="noreferrer"><i... | <p>Use the <strong><code>set_facecolor(color)</code> method of the <code>axes</code> object</strong>, which you've created one of the following ways:</p>
<ul>
<li><p>You created a figure and axis/es together</p>
<pre><code>fig, ax = plt.subplots(nrows=1, ncols=1)
</code></pre></li>
<li><p>You created a figure, then a... | 1,025 |
matplotlib | How to remove xticks from a plot | https://stackoverflow.com/questions/12998430/how-to-remove-xticks-from-a-plot | <p>I have a semilogx plot and I would like to remove the xticks. I tried:</p>
<pre><code>plt.gca().set_xticks([])
plt.xticks([])
ax.set_xticks([])
</code></pre>
<p>The grid disappears (ok), but small ticks (at the place of the main ticks) remain. How to remove them?</p>
| <p>The <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tick_params.html" rel="noreferrer"><code>plt.tick_params</code></a> method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis.</p>
<p>Note that there is also <a href="https://ma... | 1,026 |
matplotlib | Installation Issue with matplotlib Python | https://stackoverflow.com/questions/21784641/installation-issue-with-matplotlib-python | <p>I have issue after installing the <strong>matplotlib</strong> package unable to <strong>import matplotlib.pyplot as plt</strong>. Any suggestion will be greatly appreciate. </p>
<pre><code>>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
File "<stdin>", line 1, in <module&... | <p><strong>Problem Cause</strong></p>
<p>In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os. </p>
<p><strong... | 1,027 |
matplotlib | How to draw vertical lines on a given plot | https://stackoverflow.com/questions/24988448/how-to-draw-vertical-lines-on-a-given-plot | <p>Given a plot of a signal in time representation, how can I draw lines marking the corresponding time index?</p>
<p>Specifically, given a signal plot with a time index ranging from 0 to 2.6 (seconds), I want to draw vertical red lines indicating the corresponding time index for the list <code>[0.22058956, 0.33088437,... | <p>The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is <code>plt.axvline</code></p>
<pre><code>import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)
</code></pre>
<p>OR</p>
<pre><c... | 1,028 |
matplotlib | How to add a title to each subplot | https://stackoverflow.com/questions/25239933/how-to-add-a-title-to-each-subplot | <p>I have one figure which contains many subplots.</p>
<pre><code>fig = plt.figure(num=None, figsize=(26, 12), dpi=80, facecolor='w', edgecolor='k')
fig.canvas.set_window_title('Window Title')
# Returns the Axes instance
ax = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
</code></pre>
... | <p><code>ax.title.set_text('My Plot Title')</code> seems to work too.</p>
<pre><code>fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.titl... | 1,029 |
matplotlib | How to change tick label font size | https://stackoverflow.com/questions/6390393/how-to-change-tick-label-font-size | <p>In a matplotlib figure, how can I make the font size for the tick labels using <code>ax1.set_xticklabels()</code> smaller?</p>
<p>Further, how can one rotate it from horizontal to vertical?</p>
| <p>Please note that newer versions of MPL have a shortcut for this task. An example is shown in the other answer to this question: <a href="https://stackoverflow.com/a/11386056/42346">https://stackoverflow.com/a/11386056/42346</a></p>
<p>The code below is for illustrative purposes and may not necessarily be optimized.... | 1,030 |
matplotlib | Remove the legend on a matplotlib figure | https://stackoverflow.com/questions/5735208/remove-the-legend-on-a-matplotlib-figure | <p>To add a legend to a matplotlib plot, one simply runs <code>legend()</code>.</p>
<p>How to <strong>remove</strong> a legend from a plot?</p>
<p>(The closest I came to this is to run <code>legend([])</code> in order to empty the legend from data. But that leaves an ugly white rectangle in the upper right corner.)</... | <p>As of <a href="https://github.com/cimarronm/matplotlib/releases/tag/v1.4.0rc4" rel="noreferrer">matplotlib <code>v1.4.0rc4</code></a>, a <code>remove</code> method has been added to the legend object.</p>
<p>Usage:</p>
<pre class="lang-py prettyprint-override"><code>ax.get_legend().remove()
</code></pre>
<p>or</p>
... | 1,031 |
matplotlib | How to invert the x or y axis | https://stackoverflow.com/questions/2051744/how-to-invert-the-x-or-y-axis | <p>I have a scatter plot graph with a bunch of random x, y coordinates. Currently the Y-Axis starts at 0 and goes up to the max value. I would like the Y-Axis to start at the max value and go up to 0.</p>
<pre><code>points = [(10,5), (5,11), (24,13), (7,8)]
x_arr = []
y_arr = []
for x,y in points:
x_arr.append... | <p>There is a new API that makes this even simpler.</p>
<pre><code>plt.gca().invert_xaxis()
</code></pre>
<p>and/or</p>
<pre><code>plt.gca().invert_yaxis()
</code></pre>
| 1,032 |
matplotlib | How can I convert an RGB image into grayscale in Python? | https://stackoverflow.com/questions/12201577/how-can-i-convert-an-rgb-image-into-grayscale-in-python | <p>I'm trying to use <code>matplotlib</code> to read in an RGB image and convert it to grayscale.</p>
<p>In matlab I use this:</p>
<pre><code>img = rgb2gray(imread('image.png'));
</code></pre>
<p>In the <a href="http://matplotlib.sourceforge.net/users/image_tutorial.html" rel="noreferrer">matplotlib tutorial</a> the... | <p>How about doing it with <a href="https://pillow.readthedocs.io/en/latest/" rel="noreferrer">Pillow</a>:</p>
<pre><code>from PIL import Image
img = Image.open('image.png').convert('L')
img.save('greyscale.png')
</code></pre>
<hr />
<p>If an alpha (transparency) channel is present in the input image and should be pres... | 1,033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.